0

I had an array with a large amount of values that I was iterating over to find a specific value like this:

function haveValue(value) {
  for(var index in arr) {
    var prop = arr[index];
    if(prop === value) {
      return true;
    }
  }
  return false;
}

But it occurred to me that I could possibly perform this lookup much more quickly by using an object:

function haveValue(value) {
  return typeof obj[value] !== 'undefined';
}

However, I have not seen much of an improvement in performance after doing this. So I'm wondering, how are object properties stored in Javascript/Node.js? Are they basically iterated over in order to find, the same as an array? I thought they might be implemented using a hash table or something.

A. Duff
  • 4,097
  • 7
  • 38
  • 69
  • 2
    if `arr` is an `Array` you should use a `for (var i = 0; i < arr.length;i++)` loop, not a `for in` – atmd Jul 14 '15 at 13:48
  • @A.Duff - see http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Hecksa Jul 14 '15 at 13:51
  • 1
    Property access is going to be highly optimized. No engine would iterate over all the keys to find a matching one. I suggest if you try this will one million values you'll find a massive difference. –  Jul 14 '15 at 13:55
  • [`Object.prototype.hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) ? – Oka Jul 14 '15 at 13:56
  • How many elements is "large" and how often are you calling `hasValue`? – Felix Kling Jul 14 '15 at 13:56

1 Answers1

0

You've asked about iliterating through an array and if using an object would give you better performance, however you are using a for in loop for an array, and the perfromance might be better increased using a for loop or es6 includes method.

If arr is an array and you only want to check if it contains a value, you could use the es6 includes() method (docs here)

function haveValue(value) {
  return (arr.includes(value));
}

N.B. you'll need to check if your target browsers support it and shim/pollyfill if not.

if you dont want to use es6 then you can loop with a for loop

function haveValue(value) {
  for(var i = 0; i < arr.length; i++) {
    if(arr[i] === value) {
      return true;
    }
  }
  return false;
}

in your example you are using a for in loop which is really for objects not arrays. the for loop should give you better perf when used on arrays

while the size of the object might effect perf when using a string to find a value in a object (like a hashmap), the effect might be insignificant as js engines will be internally optimised.

check this jspef, selecting the first of last property of an object doesnt really effect perfromance. (obviously that effect may scale)

atmd
  • 7,430
  • 2
  • 33
  • 64