Monday, August 10, 2009

Literal Object vs. Constructor Instances

At work today we were discussing memory management with Javascript objects in regards to speeding up the front-end of the search engine. The two methods being considered were using Prototypes vs. Literal objects to store a set of data. I knocked out a quick test to see what Firefox would make of these two methods and pretty much got the results we were expecting.

Method #1 - Constructor - 1,515,056k (1.5Gb of Ram)


function blank(){
this.DOM = document.createElement( 'div' );
this.DOM.innerHTML = "Lorem ipsum dolor sit amet... ...posuere cubilia Curae.";
}

var stacked = [];

var amount = 1000000;
for( var i = 0; i < amount; i++ ){
stacked[i] = new blank;
}


Method #2 - Literal - 1,800,000k+ CRASH! (1.8Gb of Ram)


blank = {
gen: function(){
var DOM = document.createElement( 'div' );
DOM.innerHTML = "Lorem ipsum dolor sit amet... ...posuere cubilia Curae.";
return DOM;
}
}
var stacked = [];
var amount = 1000000;
for( var i = 0; i < amount; i++ ){
stacked[i] = blank.gen();
}


NOTE:
The Literal Method did not finish running. It crashed, so the memory is not truly comparable. However, the speed at which the script ran was extremely slow. The Prototype Method pumped up the memory space like a flat tire, The Literal Method crawled so slowly it felt more like trying to pour hot lead into a straw basket.

CONCLUSION:
Careful what you use those literals for!

2 comments:

  1. What's the blank.prototype.DOM; line for? You're not using it's prototype at all, shouldn't this be called Constructor vs new Object?

    cheers

    ps: your comment form is broken in FF3, had to fiddle with firebug to post this.

    ReplyDelete
  2. Oops, didn't mean to leave the blank.prototype.DOM in there. You're right, I mean constructor instances.

    ReplyDelete