public
Created

Impact on memory under different methods of object construction

  • Download Gist
Comparison.md
Markdown

Using Chrome's Heap Dump to compare the memory consumption of the two approaches:

index-lean.html: (11% retained size)

Lean

index-hog.html (52% retained size)

Hog

index-hog.html
HTML
1 2 3 4 5 6 7 8 9 10
<html>
<head>
<script type="text/javascript">
window.hogMemory = true;
</script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
index-lean.html
HTML
1 2 3 4 5 6 7 8 9 10
<html>
<head>
<script type="text/javascript">
window.hogMemory = false;
</script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
main.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/*
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());
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.