Skip to content

Instantly share code, notes, and snippets.

@mpalmerlee
Created June 18, 2016 00:34
Show Gist options
  • Save mpalmerlee/f7efabeb73236b49b8066b06ce46ab7e to your computer and use it in GitHub Desktop.
Save mpalmerlee/f7efabeb73236b49b8066b06ce46ab7e to your computer and use it in GitHub Desktop.
Javascript performance strangeness: it seems doing a conditional test and assignment is faster than an assignment alone...
var myObj = {};
var populateObj = function(obj) { for(var i = 0; i < 10000; i++) { if(i%5==0)obj[i] = i; } };
//populateObj(myObj);
console.time('test-and-assign');
for(var i = 0; i < 10000; i++) {
if(!myObj[i]){
myObj[i] = i;
}
}
console.timeEnd('test-and-assign');
var myObj = {};
//populateObj(myObj);
console.time('coalesce');
for(var i = 0; i < 10000; i++) {
myObj[i] = myObj[i] || i;
}
console.timeEnd('coalesce');
var myObj = {};
//populateObj(myObj);
console.time('control');
for(var i = 0; i < 10000; i++) {
myObj[i] = i;
}
console.timeEnd('control');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment