-1

Let's say that I'm dealing with arrays that could have 100 or more elements, and that I constantly need to search for content in these arrays. Could sorting them improve the performance of using built-in Array iterator methods like Array.prototype.forEach or Array.prototype.find?

Manuel
  • 2,143
  • 5
  • 20
  • 22
  • 2
    That depends entirely upon your use case... please elaborate further. – Jack Mar 05 '17 at 20:57
  • With ~100 elements you won't see any significant speed difference. – 4castle Mar 05 '17 at 20:58
  • Better still is to use a `Map`. – trincot Mar 05 '17 at 21:00
  • @trincot Care to explain why do you think so? Anyways, wouldn't be better to use just simple `for` loop? – kind user Mar 05 '17 at 21:01
  • Do you mean something like in this case: [Why is it faster to process a sorted array than an unsorted array?](http://stackoverflow.com/q/11227809/4642212)? – Sebastian Simon Mar 05 '17 at 21:01
  • @Kinduser I find that using built-in Array methods are simpler and takes less effort to write them. That's why I'm wondering if sorting arrays would help improve their performance. – Manuel Mar 05 '17 at 21:02
  • Isn't `for` loop a build-in method? And just to precise - are you looking for simpler and easy-writable **or** fast with high performance solution? – kind user Mar 05 '17 at 21:04
  • @Kinduser, I'm talking about methods specific to the Array object in Javascript. Like forEach() or filter() or find() or shift(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2 – Manuel Mar 05 '17 at 21:05
  • Then the `Array#forEach` solution is what you are looking for, imo. As far as I know, `forEach` doesn't return anything, that's why it works faster then `map`. But if I'm wrong, please correct me. – kind user Mar 05 '17 at 21:07
  • please add some data to get an idea, what are you looking for. – Nina Scholz Mar 05 '17 at 21:59

2 Answers2

0

Array.prototype.forEach or Array.prototype.find are both iterating through the array. Array.prototype.find will be returning first element that satisfies the conditions in the callback function, otherwise it will also iterate the entire array. So sorting won't help you with these functions but it will help you if you are using something like a binary search function.

Tim Hysniu
  • 1,446
  • 13
  • 24
0

It depends on what basis you are requesting the item that you need. A preset order of lining the items might not help you with access time if you have a different logic per search like picking an item starting with a random character. You best use a Map object or a hash table i would say...

Redu
  • 25,060
  • 6
  • 56
  • 76