CSS Parsers

JavaScript performance comparison

Test case created by Jason Miller

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var cssParserTokenizer = /\s*([a-z\-]+)\s*:\s*([^;]*?)\s*(?:;|$)/gi,
      substr2Reg = /^\s*([a-z\-]+)\s*:\s*(.*?)\s*$/gi,
      trimReg = /(^\s+|\s+$)/gi,
      cssString = 'display:block; top:1px ; width: 90%;height :50%',
      cssString2 = 'left: 10px;',
      cssString3 = 'position: absolute; display: block; left: 0px; top: 0px; width: 100%; height: 100%; padding: 0px; margin: 0px; color: rgb(157, 221, 100); border: none; overflow: hidden; font-family: Monaco, freemono, \'Courier New\', monospace; font-style: normal; font-variant: normal; font-weight: normal; background-color: rgb(25, 25, 25); font-size: 13px; line-height: 15px; background-position: initial initial; background-repeat: initial initial; ',
      output;
  
  var regexParse = function(css) {
  	var obj, token;
  	if (css) {
  		obj = {};
  		cssParserTokenizer.lastIndex = 0;
  		while ((token=cssParserTokenizer.exec(css))) {
  			obj[token[1].toLowerCase()] = token[2];
  		}
  	}
  	return obj;
  };
  
  var substringParse = function(css) {
  	var obj, parts, i, p;
  	if (css) {
  		obj = {};
  		parts = css.split(';');
  		for (i=0; i<parts.length; i++) {
  			p = parts[i].split(':');
  			if (p.length===2) {
  				obj[p[0].replace(trimReg,'').toLowerCase()] = p[1].replace(trimReg,'');
  			}
  		}
  	}
  	return obj;
  };
  
  var substringParse2 = function(css) {
  	var obj, parts, i, p;
  	if (css) {
  		obj = {};
  		parts = css.split(';');
  		for (i=0; i<parts.length; i++) {
  			substr2Reg.lastIndex = 0;
  			p = substr2Reg.exec(parts[i]);
  			if (p && p[1]) {
  				obj[p[1].toLowerCase()] = p[2];
  			}
  		}
  	}
  	return obj;
  };

};

Benchmark.prototype.teardown = function() {
  substringParse = regexParse = output = cssString = trimReg = cssParserTokenizer = null;

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Substring
output = substringParse(cssString);
output = substringParse(cssString2);
output = substringParse(cssString3);
pending…
RegExp
output = regexParse(cssString);
output = regexParse(cssString2);
output = regexParse(cssString3);
pending…
RegExp + Substring
output = substringParse2(cssString);
output = substringParse2(cssString2);
output = substringParse2(cssString3);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments