Skip to content

Instantly share code, notes, and snippets.

@robpalme
Created August 15, 2017 09:21
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 robpalme/5f5dc9352a860230af8c119fffa66d34 to your computer and use it in GitHub Desktop.
Save robpalme/5f5dc9352a860230af8c119fffa66d34 to your computer and use it in GitHub Desktop.
defineProperty vs standard property assignment
const TEST_LOOP_COUNT = 1e5;
const VAL = "woo";
const DESC = { value: VAL, configurable: true, enumerable: true, writable: true };
const propNames = [ "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7", "i8", "i9" ];
const PROP_COUNT = propNames.length;
function literal () {
return {
[propNames[0]]: VAL,
[propNames[1]]: VAL,
[propNames[2]]: VAL,
[propNames[3]]: VAL,
[propNames[4]]: VAL,
[propNames[5]]: VAL,
[propNames[6]]: VAL,
[propNames[7]]: VAL,
[propNames[8]]: VAL,
[propNames[9]]: VAL,
}
}
function assign () {
var obj = {};
obj[propNames[0]] = VAL;
obj[propNames[1]] = VAL;
obj[propNames[2]] = VAL;
obj[propNames[3]] = VAL;
obj[propNames[4]] = VAL;
obj[propNames[5]] = VAL;
obj[propNames[6]] = VAL;
obj[propNames[7]] = VAL;
obj[propNames[8]] = VAL;
obj[propNames[9]] = VAL;
return obj;
}
function assignLoop () {
var obj = {};
for (var i=0; i<PROP_COUNT; i++) {
obj[propNames[i]] = VAL;
}
return obj;
}
function defineProperty () {
var obj = {};
Object.defineProperty(obj, propNames[0], DESC);
Object.defineProperty(obj, propNames[1], DESC);
Object.defineProperty(obj, propNames[2], DESC);
Object.defineProperty(obj, propNames[3], DESC);
Object.defineProperty(obj, propNames[4], DESC);
Object.defineProperty(obj, propNames[5], DESC);
Object.defineProperty(obj, propNames[6], DESC);
Object.defineProperty(obj, propNames[7], DESC);
Object.defineProperty(obj, propNames[8], DESC);
Object.defineProperty(obj, propNames[9], DESC);
return obj;
}
function definePropertyLoop () {
var obj = {};
for (var i=0; i<PROP_COUNT; i++) {
Object.defineProperty(obj, propNames[i], DESC);
}
return obj;
}
// Measurement Infrastructure
function test (fn) {
var container = [];
for (var i=0; i<TEST_LOOP_COUNT; i++) {
container.push(fn());
}
return container;
}
var OBJECT_CREATOR_FNS = [
literal,
assign,
assignLoop,
defineProperty,
definePropertyLoop,
]
// Warmup
for (const fn of OBJECT_CREATOR_FNS) {
test(fn);
}
// Measure
for (const fn of OBJECT_CREATOR_FNS) {
console.time(fn.name);
var ret = test(fn);
console.timeEnd(fn.name);
if (ret.length !== TEST_LOOP_COUNT) { throw e; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment