Minimize string creation in dhtml widgets
I wrote a component tonight which allows me to easily bind client-side pop-up menu's to objects on a web page. A single menu is basically a Html TABLE with a collection of child menu-items represented by DIV's. Because there is a high liklehood of menu's being created over and over again I decided that I would take steps to minimize the amount of string building by “caching” the html for the menu and each menu-item the first time that it is generated. I liked it so much that I thought I'd blog it :-) Here is the GetHtml method for the menu which caches it's chunk of Html in the array variable named _stringIntern_ the first time that it is generated and pulls it from there on subsequent rendering operations. The same logic is followed for each menu-item.
var _stringIntern_ = new Array() ;
Menu.prototype.GetHtml = function()
{
if(this.IsInterned())
return _stringIntern_[this.Id] ;
var s = "<table class=\"dhtmlmMenuTable\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" border=\"0\">\n" ;
for( var i = 0; i < this.MenuItems.length; i++ )
{
s += "\t<tr>\n\t\t<td>\n\t\t\t" ;
s += this.MenuItems[i].GetHtml() ;
s += "\n\t\t</td>\n\t</tr>\n" ;
}
s += "</table>" ;
this.Intern(s) ;
return s ;
}
Menu.prototype.Intern = function( s )
{
_stringIntern_[this.Id] = s ;
}
Menu.prototype.IsInterned = function()
{
return( _stringIntern_[this.Id] != 'undefined' )
}