Created
May 23, 2010 23:57
-
-
Save drench/411371 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var timethis = function (f, n) { | |
var start = new Date(); | |
for (var i=n; i > 0; --i) f(); | |
var end = new Date(); | |
var delta = end.getTime() - start.getTime(); | |
print(n + ' iterations took ' + delta + 'ms'); | |
}; | |
var switchcase = function (tag) { | |
var selfClosing = false; | |
switch(tag.toLowerCase()) { | |
case "area": | |
case "base": | |
case "basefont": | |
case "br": | |
case "hr": | |
case "input": | |
case "img": | |
case "link": | |
case "meta": | |
selfClosing = true; | |
break; | |
} | |
return selfClosing; | |
}; | |
var regex_one = function (tag) { | |
return tag.match(/^(area|base|basefont|br|hr|input|img|link|meta)$/i) ? true: false; | |
}; | |
var re = new RegExp('^(area|base|basefont|br|hr|input|img|link|meta)$', 'i'); | |
var regex_two = function (tag) { | |
return re.test(tag); | |
}; | |
var taghash = { | |
area: true, base: true, basefont: true, br: true, hr: true, input: true, | |
img: true, link: true, meta: true | |
}; | |
var hash = function (tag) { | |
return taghash[tag.toLowerCase()] ? true : false; | |
}; | |
var tags = []; | |
(function () { | |
var i = 1000; | |
var possible_tags = [ | |
'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta', | |
'a', 'b', 'blockquote', 'body', 'div', 'font', 'head', 'li', 'ol', 'q', | |
'script', 'span', 'table', 'tbody', 'td', 'thead', 'title', 'tr', 'ul' | |
]; | |
var l = possible_tags.length; | |
while (i--) { | |
tags.push( possible_tags[ Math.floor(Math.random() * l) ] ); | |
} | |
})(); | |
print('switch/case:'); | |
timethis(function () { | |
var i = tags.length; | |
while (i-- > 0) { | |
switchcase(tags[i]); | |
} | |
}, 1000); | |
print('regex version 1 (compile on each hit):'); | |
timethis(function () { | |
var i = tags.length; | |
while (i-- > 0) { | |
regex_one(tags[i]); | |
} | |
}, 1000); | |
print('regex version 2 (compile once):'); | |
timethis(function () { | |
var i = tags.length; | |
while (i-- > 0) { | |
regex_two(tags[i]); | |
} | |
}, 1000); | |
print('hash key check:'); | |
timethis(function () { | |
var i = tags.length; | |
while (i-- > 0) { | |
hash(tags[i]); | |
} | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment