Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Last active November 3, 2017 08:56
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 bmeurer/3a36fd3e3e8fecc96f9cfabc49d791f1 to your computer and use it in GitHub Desktop.
Save bmeurer/3a36fd3e3e8fecc96f9cfabc49d791f1 to your computer and use it in GitHub Desktop.
// Benchmark to measure loops running until OOB vs. loops that run
// to length. See
//
// https://v8project.blogspot.de/2017/09/elements-kinds-in-v8.html#avoid-reading-beyond-length
//
// for background. While OOB access is now no longer almost 10x
// slower in V8, it's still an anti-pattern that should be avoided.
"use strict";
function doSomething(item) {}
function testArrayInBounds(items) {
for (let i = 0; i < items.length; ++i) {
doSomething(items[i]);
}
}
function testArrayOutOfBounds(items) {
for (let i = 0, item; (item = items[i]) != null; ++i) {
doSomething(item);
}
}
function testStringInBounds(string) {
for (let i = 0; i < string.length; ++i) {
doSomething(string[i]);
}
}
function testStringOutOfBounds(string) {
for (let i = 0, char; (char = string[i]) != null; ++i) {
doSomething(char);
}
}
const N = 1e7;
const F = [
testArrayInBounds,
testArrayOutOfBounds,
testStringInBounds,
testStringOutOfBounds
];
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function test(f, n) {
var result;
for (var i = 0; i < n; ++i) {
result = f(items);
}
return result;
}
// Warmup
test(x => x, 50);
for (var i = 0; i < 10; ++i) {
for (var f of F) test(f, 50);
}
// Measure
for (var f of F) {
var start = Date.now();
var o = test(f, N);
var end = Date.now();
console.log(f.name + ": " + (end - start) + " ms.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment