Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Created August 14, 2017 07:49
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/6ad8e8ffb36e2a0e70a68819071d7e7f to your computer and use it in GitHub Desktop.
Save bmeurer/6ad8e8ffb36e2a0e70a68819071d7e7f to your computer and use it in GitHub Desktop.
Micro-benchmark to demonstrate for-in regression with Node 8.3.0 (https://github.com/davidmarkclements/v8-perf/blob/master/bench/object-iteration.js)
if (typeof console === 'undefined') console = {log:print};
function forIn(o) {
var result = 0;
for (var i in o) {
result += 1;
}
return result;
}
function forInHasOwnProperty(o) {
var result = 0;
for (var i in o) {
if (o.hasOwnProperty(i)) {
result += 1;
}
}
return result;
}
function forInHasOwnPropertySafe(o) {
var result = 0;
for (var i in o) {
if (Object.prototype.hasOwnProperty.call(o, i)) {
result += 1;
}
}
return result;
}
function forInSum(o) {
var result = 0;
for (var i in o) {
result += o[i];
}
return result;
}
function forInSumSafe(o) {
var result = 0;
for (var i in o) {
if (Object.prototype.hasOwnProperty.call(o, i)) {
result += o[i];
}
}
return result;
}
var TESTS = [
forIn,
forInHasOwnProperty,
forInHasOwnPropertySafe,
forInSum,
forInSumSafe
];
var o = {w:0, x:1, y:2, z:3};
var n = 1e8;
function test(fn) {
var result;
for (var i = 0; i < n; ++i) result = fn(o);
return result;
}
// Warmup.
for (var j = 0; j < TESTS.length; ++j) {
test(TESTS[j]);
}
// Measure.
for (var j = 0; j < TESTS.length; ++j) {
var startTime = Date.now();
test(TESTS[j]);
console.log(TESTS[j].name + ':', (Date.now() - startTime), 'ms.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment