Skip to content

Instantly share code, notes, and snippets.

@jimmielemontgomery
Last active November 26, 2018 21:36
Show Gist options
  • Save jimmielemontgomery/f6a5e3bbad11f0749e0045a65e50d087 to your computer and use it in GitHub Desktop.
Save jimmielemontgomery/f6a5e3bbad11f0749e0045a65e50d087 to your computer and use it in GitHub Desktop.
checks for invalidating assertions
// perf of keys and key length, generally Object.keys vs _.keys
function test(o, a, b, len=10){
var i = 0, name = a.name || 'run1';
console.time(name);
while(len > i++){
a(o).length;
}
console.timeEnd(name);
i = 0, name = b.name || 'run2';
console.time(name);
while(len > i++){
b(o).length;
}
console.timeEnd(name);
}
function key1(o){ return _.keys(o); }
function key2(o){ return Object.keys(o); }
function key3(o){ return _.keys(o).length; }
function key4(o){ return 'number' === typeof o.length ? o.length : Object.keys(o).length; }
function key5(o){ return Array.isArray(o) ? o.length : Object.keys(o).length; }
test(window, key1, key2, 10000);
test((new Array(1478)).fill(2), key1, key2, 10000);
test(window, key3, key4, 10000);
test((new Array(1478)).fill(2), key3, key4, 10000);
test(window, key3, key5, 10000);
test((new Array(1478)).fill(2), key3, key5, 10000);
/* results: {} vs [], keys, keys.length:
key1: 1230.218017578125ms
key2: 288.373046875ms
key1: 1159.56396484375ms
key2: 164.333984375ms
key3: 1183.18896484375ms
key4: 1.952880859375ms
key3: 1133.85205078125ms
key4: 0.1689453125ms
key3: 1162.194091796875ms
key5: 279.9951171875ms
key3: 1133.153076171875ms
key5: 0.669189453125ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment