Skip to content

Instantly share code, notes, and snippets.

@iammerrick
Created May 10, 2013 16:33
Show Gist options
  • Save iammerrick/5555590 to your computer and use it in GitHub Desktop.
Save iammerrick/5555590 to your computer and use it in GitHub Desktop.
Prototype vs. Instance
function Person(name) {
this.name = name;
this.greet = function() {
console.log('Hello ' + this.name);
}
this.setName = function(name) {
this.name = name;
}
}
var cache = [];
for (var i = 0; i < 1e6; i++) {
cache.push(new Person('Merrick'));
}
console.log(JSON.stringify(process.memoryUsage()));
Prototype creation was cheaper by 145.2164764404297 MB
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello ' + this.name);
}
Person.prototype.setName = function(name) {
this.name = name;
}
var cache = [];
for (var i = 0; i < 1e6; i++) {
cache.push(new Person('Merrick'));
}
console.log(JSON.stringify(process.memoryUsage()));
var exec = require('child_process').exec;
var mb = 1048576;
exec('node Instance.js',
function (error, stdout, stderr) {
var instance = JSON.parse(stdout);
exec('node Prototype.js',
function (error, stdout, stderr) {
var proto = JSON.parse(stdout);
if (instance.heapUsed < proto.heapUsed) {
console.log('Instance creation was cheaper by '+ ((proto.heapUsed - instance.heapUsed) / mb)+ ' MB');
} else {
console.log('Prototype creation was cheaper by '+ ((instance.heapUsed - proto.heapUsed)/ mb)+ ' MB');
}
});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment