Skip to content

Instantly share code, notes, and snippets.

@a-laughlin
Last active May 1, 2017 03:04
Show Gist options
  • Save a-laughlin/23701e706fbeeba172a986bafd412f32 to your computer and use it in GitHub Desktop.
Save a-laughlin/23701e706fbeeba172a986bafd412f32 to your computer and use it in GitHub Desktop.
memory allocation of different js objects
window.__MemoryTest__ = {
proto:[],
concat:[],
creat:[],
newFn:[],
factory:[]
};
function proto(){return new Foo()}
function concat(){return Object.assign({},baseObj)}
function creat(){return Object.create(baseObj)}
function newFn(){return ({fn:function(){}})}
function factory(){return ({fn:baseObj.fn})}
var creatorFns = {proto,concat,creat,newFn,factory};
var baseObj = {
fn:function(){}
};
function Foo(){}
Foo.prototype = baseObj;
Object.keys(creatorFns).forEach((name)=>{
const fn = creatorFns[name];
const resultArray = window.__MemoryTest__[name];
let loop = 100000;
console.profile(name);
while(loop--) resultArray[loop] = fn();
console.profileEnd(name);
});
// prototypes mostly useful when objects are thrashing lots of memory
// like in 60fps games creating many objects... which few people ever do
// or tables with millions of rows
// even then, there are other ways to gain performance improvements,
// - referencing other objects
// - object pools
// - pass in the fns you need
// - optimize IO since web apps are usually IO bound
// arrayName, arrayBytes, oneObjBytes
// newFn 11316240 104 // ~9 million objects per gb
// creat 6515872 56 // ~18 million objects per gb
// concat 6515784 56 // ~18 million objects per gb
// factory 4115784 32 // ~31 million objects per gb
// proto 3315784 24 // ~42 million objects per gb
// Oddly, factory's objects are more space efficient than Object.create's, despite the prototype.
// also odd is the array size discrepancy with concat and creat
// factory seems to have the the best size performance if new objects are needed.
// no time to test execution performance tonight
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment