Created
July 7, 2017 14:23
-
-
Save peterwmwong/b05126e2a0b54a5454db2fefdd2b1605 to your computer and use it in GitHub Desktop.
Comparing for-loop vs Array.p.map
This file contains hidden or 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
'use strict'; | |
/* | |
Checked CL out using... | |
> git fetch https://chromium.googlesource.com/v8/v8 refs/changes/39/548639/17 && git checkout FETCH_HEAD | |
> d8 --turbo_inline_array_builtins --allow-natives-syntax map.js | |
doArrayMap 2194 ms | |
doForLoop 879 ms | |
> d8 --allow-natives-syntax map.js | |
doArrayMap 2188 ms | |
doForLoop 863 ms | |
*/ | |
function doForLoop(arr) { | |
const result = []; | |
for(let i=0; i<arr.length; ++i) { | |
const c = arr[i]; | |
result.push(c + c); | |
} | |
return result; | |
} | |
function doArrayMap(arr) { return arr.map(c => c + c); } | |
const ARRAYS = [ | |
[0,1,2,3,4,5], | |
[5,0,1,2,3,4], | |
[4,5,0,1,2,3], | |
// ['0','1','2','3','4','5'], | |
// [{a: 0},{a: 1},{a: 2},{a: 3},{a: 4},{a: 5}] | |
]; | |
function bench(func, max){ | |
const start = Date.now(); | |
for (let i = 0; i < max; ++i) { | |
func(ARRAYS[i % ARRAYS.length]); | |
} | |
const end = Date.now(); | |
return `${func.name} ${end - start} ms`; | |
} | |
// Speculation: Prevent one function getting an advantage (inlining?) on the other. | |
%NeverOptimizeFunction(bench); | |
// Warmup | |
bench(doArrayMap, 5); | |
bench(doForLoop, 5); | |
%OptimizeFunctionOnNextCall(doArrayMap); | |
%OptimizeFunctionOnNextCall(doForLoop); | |
bench(doArrayMap, 5); | |
bench(doForLoop, 5); | |
// Bench | |
print(bench(doArrayMap, 1e7)); | |
print(bench(doForLoop, 1e7)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment