Skip to content

Instantly share code, notes, and snippets.

@starkovsky
Last active September 26, 2024 08:07
Show Gist options
  • Save starkovsky/4c5668e2d172c29cdd44725d7107c334 to your computer and use it in GitHub Desktop.
Save starkovsky/4c5668e2d172c29cdd44725d7107c334 to your computer and use it in GitHub Desktop.
test array methods js
// Crteate arr of x el
const arr = [];
const x = 1000000;
for (let i = 0; i < x; i++) {
arr.push(i);
}
// O(n^2) map -> filter
function test1() {
const arr1 = arr.map(n => n*4).filter(n => n > 300);
}
// O(n) filter
function test2() {
const arr3 = arr.filter(n => n*4 > 300);
}
// O(n) for of
function test3() {
const arr2 = [];
for(n of arr) {
const m = n*4;
if (m > 300) {
arr2.push(m);
}
}
}
// O(n) for
function test4() {
const arr4 = [];
for(let i = 0; i < arr.length; i++) {
const m = arr[i]*4;
if (m > 300) {
arr4.push(m);
}
}
}
// Iterations
const y = 100;
console.time(`test1`);
for(let i = 0; i < y; i++) {
test1();
}
console.timeEnd(`test1`);
console.time(`test2`);
for(let i = 0; i < y; i++) {
test2();
}
console.timeEnd(`test2`);
console.time(`test3`);
for(let i = 0; i < y; i++) {
test3();
}
console.timeEnd(`test3`);
console.time(`test4`);
for(let i = 0; i < y; i++) {
test4();
}
console.timeEnd(`test4`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment