JavaScript Optimization, Part 2

I’ve long longed for a JavaScript equivalent to PHP’s in_array() method. It’s a simple function to write, but perhaps not so easy to write right. Mike Brittain offers up a version that works well for relatively small arrays. But, there are tricks to optimizing JavaScript, so I decided to see how much effect they might have on his ever-so-functional function.

The following test searches for several of the 4,567 PHP function names contained in an array (and a couple values that do not exist in the array) by assigning a search method to the Array prototype, then timing how long it takes to retreive the result.

Perhaps not surprisingly, the results are consistent with the results of my previous test.

Update: Thanks to some helpful comments over at Code Lab, I have updated my in_array_minus method to account for arrays with no elements.

Update II: Thanks to "Sebastian" for alertly spotting a bug in in_array_minus. As he pointed out, it should be var i = this.length - 1;, not var i = this.length;.

Update III: Sebastian's change introduced a bug I should have noticed where false would always be returned when searching an array with only 1 item. This has been fixed by changing if (i > 0) { to if (i >= 0) {. Thanks to Joshua Chan for pointing this out!

Array.prototype.in_array_plus = 
         function(search_term) {
   for (var i = 0; i < this.length; i++) {
      if (this[i] === search_term) {
         return true;
      }
   }
   return false;
}
 
Click the button to test
Elapsed time:
Array.prototype.in_array_minus = function(search_term) {
  var i = this.length - 1;
  if (i >= 0) {
	 do {
		if (this[i] === search_term) {
		   return true;
		}
	 } while (i--);
  }
  return false;
}
Click the button to test
Elapsed time:

 

Was this page useful to you? Loading...