Using Chrome's Heap Dump to compare the memory consumption of the two approaches:
index-lean.html: (11% retained size)
index-hog.html (52% retained size)
<html> | |
<head> | |
<script type="text/javascript"> | |
window.hogMemory = true; | |
</script> | |
<script type="text/javascript" src="main.js"></script> | |
</head> | |
<body> | |
</body> | |
</html> |
<html> | |
<head> | |
<script type="text/javascript"> | |
window.hogMemory = false; | |
</script> | |
<script type="text/javascript" src="main.js"></script> | |
</head> | |
<body> | |
</body> | |
</html> |
/* | |
Defining your methods inside the constructor function | |
causes them to be re-created every single time that | |
function is run, wasting a huge amount of memory when the functions are non-trivial. | |
*/ | |
function SomeConstructor() { | |
function methodOne() { | |
console.log("Just some code"); | |
console.log("Just some code"); | |
console.log("Just some code"); | |
for (i = 0; i < 10; ++i) { | |
someVar *= 2; | |
} | |
} | |
function methodTwo() { | |
console.log("Need something in our method bodies"); | |
console.log("to use memory"); | |
} | |
function methodThree() { | |
var i,h,j = 0; | |
i = Math.random() * 55; | |
h = Math.random() * 2; | |
j = Math.random() * -1; | |
return i * h + j - h; | |
} | |
return { | |
constructor: SomeConstructor, | |
m1: methodOne, | |
m2: methodTwo, | |
m3: methodThree | |
}; | |
} | |
function SomeOtherConstructor() { | |
} | |
/* | |
Defining your methods on the prototype causes them to only ever be created once instead of | |
every time an instance of your object is created. | |
*/ | |
SomeOtherConstructor.prototype = { | |
m1: function() { | |
console.log("Just some code"); | |
console.log("Just some code"); | |
console.log("Just some code"); | |
for (i = 0; i < 10; ++i) { | |
someVar *= 2; | |
} | |
}, | |
m2: function() { | |
console.log("Need something in our method bodies"); | |
console.log("to use memory"); | |
}, | |
m3: function() { | |
var i,h,j = 0; | |
i = Math.random() * 55; | |
h = Math.random() * 2; | |
j = Math.random() * -1; | |
return i * h + j - h; | |
} | |
} | |
var NUM_OBJECTS = 10000; | |
window.objects = []; | |
if (window.hogMemory) { | |
for (i = 0; i < NUM_OBJECTS; ++i) { | |
objects.push(SomeConstructor()); | |
} | |
console.log("Hogged memory"); | |
} else { | |
for (i = 0; i < NUM_OBJECTS; ++i) { | |
objects.push(new SomeOtherConstructor()); | |
} | |
} |