benchmarks
by evgkch
JavaScript
/*
* Creating and filling array benchmark
*/
function randomNumber(max){
return Math.floor(Math.random() * max);
}
console.time('arr_1 created by loop');
const arr_1 = [];
for (let i = 0; i < 100000; i++){
arr_1.push(randomNumber(100000));
}
console.timeEnd('arr_1 created by loop');
console.time('arr_2 created from Array');
const arr_2 = Array.from({ length: 100000 }, (v,k)=>randomNumber(100000));
console.timeEnd('arr_2 created from Array');
console.log('deleting some elements for arr_1 and setting nulls for arr_2');
for (let i = 0; length = arr_1.length, i < length; i++){
if (Math.random() < 0.5)
{
delete arr_1[i];
arr_2[i] = null;
}
}
const res_1 = [];
const res_2 = [];
console.time('loopping arr_1 after deleting');
for (let i = 0; length = arr_1.length, i < length; i++){
res_1.push(arr_1[i]);
}
console.timeEnd('loopping arr_1 after deleting');
console.time('loopping arr_2 after rewriting');
for (let i = 0; length = arr_2.length, i < length; i++){
res_2.push(arr_2[i]);
}
console.timeEnd('loopping arr_2 after rewriting');