Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36
Chrome 129
Windows
Desktop
5 months ago
Test name Executions per second
Math.max.apply 388497.8 Ops/sec
Math.max with spread 72792.5 Ops/sec
basic for loop 2276.8 Ops/sec
for loop length caching 3607.3 Ops/sec
for loop reverse 3426.7 Ops/sec
for-of loop 6517.2 Ops/sec
Math.max.apply extracted into separate function 4688712.5 Ops/sec
Script Preparation code:
x
 
var arr = [];
var max = -Infinity;
for (i = 0; i < 4096; i++) { 
  arr.push(Math.random() * i);
}
function mathMax (array) {
    return Math.max.apply(Math, array);
}
Tests:
  • Math.max.apply

     
    max = Math.max.apply(Math, arr);
  • Math.max with spread

     
    max = Math.max(...arr);
  • basic for loop

     
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] > max) {
        max = arr[i];
      }
    }
  • for loop length caching

     
    for (let i = 0, len = arr.length; i < len; i++) {
      if (arr[i] > max) {
        max = arr[i];
      }
    }
  • for loop reverse

     
    for (let i = arr.length - 1; i >= 0; i--) {
      if (arr[i] > max) {
        max = arr[i];
      }
    }
  • for-of loop

     
    for (const value of arr) {
      if (value > max) {
        max = value;
      }
    }
  • Math.max.apply extracted into separate function

     
    mathMax(arr)