Last active
January 19, 2017 02:22
-
-
Save vsemozhetbyt/6679914bad0c3098e7ee666abe500a3d to your computer and use it in GitHub Desktop.
Benchmark cycles
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'; | |
| /******************************************************************************/ | |
| // via https://twitter.com/bmeurer/status/821804688454680576 | |
| console.log(` | |
| // v8 ${process.versions.v8} (Node.js ${process.versions.node}) | |
| `); | |
| function f1(a) { | |
| let x = 0; | |
| for (let i = 0, l = a.length; i < l; ++i) x += a[i]; | |
| return x; | |
| } | |
| function f2(a) { | |
| let x = 0; | |
| for (const y of a) x += y; | |
| return x; | |
| } | |
| function f3(a) { | |
| let x = 0; | |
| a.forEach((y) => { x += y; }); | |
| return x; | |
| } | |
| const a = []; | |
| for (let i = 0; i < 1000; ++i) a[i] = i; | |
| function bench(f) { | |
| for (let i = 0; i < 1000; ++i) f.call(null, a); | |
| } | |
| for (let i = 0; i < 10; ++i) { | |
| bench(f1); | |
| bench(f2); | |
| bench(f3); | |
| } | |
| console.time('for '); | |
| bench(f1); | |
| console.timeEnd('for '); | |
| console.time('for-of '); | |
| bench(f2); | |
| console.timeEnd('for-of '); | |
| console.time('forEach'); | |
| bench(f3); | |
| console.timeEnd('forEach'); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this more resumptive benchmark with some results in the comments for several v8 / Node.js versions.