Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Created November 6, 2017 12:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmeurer/028ae4e4f559ed963402f4ae1a2d50c0 to your computer and use it in GitHub Desktop.
Save bmeurer/028ae4e4f559ed963402f4ae1a2d50c0 to your computer and use it in GitHub Desktop.
// Benchmark for the PR https://github.com/babel/babel/pull/6748
"use strict";
// Object with no enumerable properties in the prototype chain.
const a = {x:1, y:2, z:3};
// Object with enumerable properties in the prototype chain.
function B() { this.x = 1; this.y = 2; this.z = 3; }
B.prototype.foo = 4;
const b = new B;
function testForInClean() {
let result = 0;
for (const k in a) {
if (Object.prototype.hasOwnProperty.call(a, k)) {
result += a[k];
}
}
return result;
}
function testForInPolluted() {
let result = 0;
for (const k in b) {
if (Object.prototype.hasOwnProperty.call(b, k)) {
result += b[k];
}
}
return result;
}
function testObjectKeysClean() {
let result = 0;
Object.keys(a).forEach(k => {
result += a[k];
});
return result;
}
function testObjectKeysPolluted() {
let result = 0;
Object.keys(b).forEach(k => {
result += b[k];
});
return result;
}
function testObjectKeysForOfClean() {
let result = 0;
for (const k of Object.keys(a)) {
result += a[k];
}
return result;
}
function testObjectKeysForOfPolluted() {
let result = 0;
for (const k of Object.keys(b)) {
result += b[k];
}
return result;
}
const N = 1e7;
const F = [
testForInClean,
testForInPolluted,
testObjectKeysClean,
testObjectKeysPolluted,
testObjectKeysForOfClean,
testObjectKeysForOfPolluted
];
function test(f, n) {
var result;
for (var i = 0; i < n; ++i) {
result = f(1);
}
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