Thursday Apr 03, 2008

A SAX Parser Based on JavaScript's String.replace() Method?

I've often wished browsers would offer native SAX implementations. SAX is lightweight and fast. Not only that, SAX is easy because it lets you ignore what's not interesting, unlike DOM, where you have to traverse the whole mess and keep it hanging around in memory. SAX also uses callback functions, which any JavaScript programmer should feel comfortable with.

[Read More]

Sunday Jan 27, 2008

Pre-compile and cache yer dang regular expressions

We have a function called hasClassName(el, cls) that checks whether a given DOM element has a given class. More and more, we're relying heavily on this function, and on certain pages it can run thousands of times. In these situations a little performance tuning can go a long way, as demonstrated here:

// BEFORE
function hasClassName(el, cls){
  var exp = new RegExp("(\^|\\\\s)"+cls+"($|\\\\s)");
  return (el.className && exp.test(el.className))?true:false;
}
// AFTER
(function(){
  var c={};//cache regexps for performance
  window.hasClassName=function(el, cls){
    if(!c[cls]){c[cls]=new RegExp("(\^|\\\\s)"+cls+"($|\\\\s)");}
    return el.className && c[cls].test(el.className);
  }
})();

This simple change cut the function's average runtime in half and reduced the page's overall onload setup time by over 25%! (According to Firebug.) All because it caches regular expressions.

Edit: removed unnecessary ?: operator per Nate's comment.

About

My name is Greg Reimer and I'm a web technologist for the Sun.COM web design team.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
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
   
       
Today