ShowUsYour<Blog>

Irregular expressions regularly

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.


// interning table
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 ; } // GetHtml Menu.prototype.Intern = function( s ) { _stringIntern_[this.Id] = s ; } Menu.prototype.IsInterned = function() { return( _stringIntern_[this.Id] != 'undefined' ) }

Comments

jeff said:

Just a suggestion, but you might also gain a slight performance boost by using StringBuilder instead of concatenating strings.
# January 28, 2004 10:50 AM

Darren Neimke said:


LOL, hey Jeff, that's client-side javascript by the way :)
# January 28, 2004 3:08 PM

Damon said:

Is this component going to be available or is there a demo somewhere?
# January 28, 2004 7:26 PM

Darren Neimke said:


Hi Damon, yes, I'm planning to release it as an Assembly (with source) as a GotDotNet sample sometime in the next month. Keep your eyes on my blog and I'll try to blog about my progress in the next week or 2; I'll also discuss a little bit about how I plan that it will work. I'll add those entries to my "Tools" category.

Cheers,
- Darren
# January 28, 2004 8:17 PM

TrackBack said:

# January 30, 2004 11:11 AM

Voyuer Ametuers said:

eh... bookmarked post ))

# December 20, 2009 11:30 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)