When creating a function in javascript its a good idea to check object the object type(s) of the arguments pasted to function. Lots of times you end up with code looking like this to do this
if(typeof(foo)=='undefined'|| foo==''){ ////do something }
Earlier this week I ran across Paul Irish's jQuery Anti-Patterns for Performance & Compression. In there he mentioned using a regular expression to check to see if a variable contains a value.
//from the slide in the presentation //instead of this if(type=='foo'||type==bar){ } //use this if(/^(foo|bar)$/.test(type)){ }
That got me thinking, would it the code above be faster even if I added to the regular expression to check the type? So I crafted a quick exprement. He is my test code
function bar(foo){ //console.log(typeof(foo)); console.time('regex'); if(/^(\s)*$|^(undefined)+$/.test(foo)){ //console.log('regex') } console.timeEnd('regex'); console.time('typeof'); if(typeof(foo)=='undefined'|| foo==''){ ////console.log('||'); } console.timeEnd('typeof'); } bar('');
Time taken over 50 literations
argument value/type | /^(\d)*|(undefined)+$/.test(foo) | typeof(foo)=='undefined'|| foo=='' |
---|---|---|
undefined | 12ms | 10ms |
'' | 8ms | 12ms |
As you can see its pretty much a wash when the argument is the undefined. But when when the value is an empty string this method very fast. Granted that my test has a very small scope, but its enough to convince me that using a regular expression to check the type/value is a good practice.