3 ms·
It might be faster to write the code, but it's definitely not the fastest way to find the minimum/maximum value. Some simple test cases I wrote show a simple f
by utkarshkukreti 16y ago
It might be faster to write the code, but it's definitely not the fastest way to find the minimum/maximum value. Some simple test cases I wrote show a simple for loop iterator over an array to be 2x faster than Math.min.apply in Firefox 4, and 3x faster in Chrome 10.
http://jsperf.com/fastest-array-min-max http://jsperf.com/fastest-array-min-max
- dspillett 16y agoIf you take out the (currently unused: it is updated but never referred to afterwards) the first-index-of-the-smallest-value-was-found-at variable the difference in FF is even larger. These are the results on FF 3.6.16 on my desktop: ~33.5 ops/sec (million test, using Array.min.apply) ~57.0 o/s (with index var) ~86.5 o/s (without index var) I'm a little surprised it makes that much difference (I assumed the two set operations, one of which I removed, would be less significant than that in the execution timings compared to the array object lookup in the comparison, given JS arrays aren't actually arrays strictly speaking). The difference may be less significant (zero, in fact) with a JS engine that does dead-code analysis that successfully works out that min_i is set in the loop but otherwise never used.
- utkarshkukreti 16y agoAh yes, there was no need of using min_i in my benchmark. That's a pretty big difference, and I wouldn't have expected that much of a difference for assigning one extra variable in the loop.