Search code examples
javascriptperformancetyped-arrays

Using Math.max with typed subarrays


I have a typed array filled with values.

I am trying to figure out the fastest way to calculate the max and min of those values in any given boundary.

So for example, I have 3200 values and I want to know the max value of the range between index 342 and 934, the boundary range can change and reach from a 1000 values to check on to multiple ten thousands.

I thought that something like this would work:

const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
Math.max(...a.subarray(5, 7)); // Returns 45.

But as far as I remember, the spread operator is super slow.

I actually thought that the Math.max function also takes an array but using

Math.max(a.subarray(5, 7));

returns NaN.

Has anybody an idea on what the most performant way would be to get the maximum of any given range? I am especially looking for high performance on large views.


Solution

  • Math.max takes any number of arguments, so you can use Math.max.apply (see Function.prototype.apply) to pass it an array:

    const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
    var max = Math.max.apply(null,a.subarray(5, 7));
    console.log(max);

    But the absolute fastest appears to be :

    const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
    var sa = a.subarray(5, 7);
    var max = -Infinity;
    for(var i=0;i<sa.length;i++)
       if(sa[i] > max) max = sa[i];
    console.log(max);

    Benchmark results: https://jsbench.me/92kfgj7ldx/1