Skip to content

Instantly share code, notes, and snippets.

@LeandroSQ
Created March 6, 2021 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeandroSQ/0fb47c33fe35b16c030e0e340ab003f2 to your computer and use it in GitHub Desktop.
Save LeandroSQ/0fb47c33fe35b16c030e0e340ab003f2 to your computer and use it in GitHub Desktop.
Javascript Map, ForI, ForOf, ForIn, ForEach and MapPromise benchmark
(() => {
function n() {
let length = Math.floor((Math.random() * 90) + 10);
let buffer = "";
for (let i = 0; i < length; i ++) {
let tmp = Math.floor(Math.random() * 26);
buffer += String.fromCharCode(65 + tmp);
}
return buffer;
}
console.log("Mounting the array...");
let array = [];
for (let i = 0; i < 1000000; i ++) {
array.push(n());
}
console.log("Array with " + array.length + " entries!");
function f (x) {
let t = x.length / 2;
let a = x.substring(0, t);
let b = x.substring(t);
return a + b;
}
let tmp = [];
console.time("map");
tmp = array.map(f);
console.timeEnd("map");
tmp = [];
console.time("fori");
for (let i = 0; i < array.length; i++) {
tmp.push(f(array[i]));
}
console.timeEnd("fori");
tmp = [];
console.time("forof");
for (let x of array) {
tmp.push(f(x));
}
console.timeEnd("forof");
tmp = [];
console.time("forin");
for (let x in array) {
if (array.hasOwnProperty(x));
tmp.push(f(array[x]));
}
console.timeEnd("forin");
tmp = [];
console.time("foreach");
array.forEach(x => tmp.push(f(x)));
console.timeEnd("foreach");
console.time("map-promise")
Promise.all(
array.map(x => {
return new Promise((resolve, reject) => {
resolve(f(x))
})
})
).then(x => console.timeEnd("map-promise"));
}) ();
@LeandroSQ
Copy link
Author

LeandroSQ commented Mar 6, 2021

Results on my machine:

map:         898.11ms
fori:        265.51ms
forof:       286.88ms
forin:       439.98ms
foreach:     279.02ms
map-promise: 2753.61ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment