将 Math.max 与类型化子数组一起使用
Using Math.max with typed subarrays
我有一个充满值的类型化数组。
我正在尝试找出计算任何给定边界内这些值的最大值和最小值的最快方法。
例如,我有 3200 个值,我想知道索引 342 和 934 之间范围的最大值,边界范围可以改变并从 1000 个值达到数万个。
我认为这样的事情会奏效:
const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
Math.max(...a.subarray(5, 7)); // Returns 45.
但据我所知,传播运算符超级慢。
我实际上认为 Math.max
函数也接受一个数组但是使用
Math.max(a.subarray(5, 7));
returns NaN
.
有没有人知道什么是获得任何给定范围的最大值的最有效方法?我特别希望在大视图上获得高性能。
Math.max
takes any number of arguments, so you can use Math.max.apply
(see Function.prototype.apply
) 传递一个数组:
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);
但绝对最快的似乎是:
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);
这是您可以使用的替代方案。
const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
Math.max.apply({}, a.subarray(5, 7));
我在 jsbench 上尝试了 运行 个基准测试,结果如下:
code block 1 (1404013)
code block 2 (1695631)
根据 specs
这就是应用程序的工作方式
我有一个充满值的类型化数组。
我正在尝试找出计算任何给定边界内这些值的最大值和最小值的最快方法。
例如,我有 3200 个值,我想知道索引 342 和 934 之间范围的最大值,边界范围可以改变并从 1000 个值达到数万个。
我认为这样的事情会奏效:
const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
Math.max(...a.subarray(5, 7)); // Returns 45.
但据我所知,传播运算符超级慢。
我实际上认为 Math.max
函数也接受一个数组但是使用
Math.max(a.subarray(5, 7));
returns NaN
.
有没有人知道什么是获得任何给定范围的最大值的最有效方法?我特别希望在大视图上获得高性能。
Math.max
takes any number of arguments, so you can use Math.max.apply
(see Function.prototype.apply
) 传递一个数组:
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);
但绝对最快的似乎是:
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);
这是您可以使用的替代方案。
const a = new Uint8Array([10, 60, 5, 90, 110, 3, 45, 1, 24, 54, 29]);
Math.max.apply({}, a.subarray(5, 7));
我在 jsbench 上尝试了 运行 个基准测试,结果如下:
code block 1 (1404013)
code block 2 (1695631)
根据 specs
这就是应用程序的工作方式