Created
March 6, 2021 20:46
-
-
Save LeandroSQ/0fb47c33fe35b16c030e0e340ab003f2 to your computer and use it in GitHub Desktop.
Javascript Map, ForI, ForOf, ForIn, ForEach and MapPromise benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
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")); | |
}) (); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on my machine: