最多可找到9个数字 - 快速

时间:2017-12-09 13:10:35

标签: javascript

我有9个随机整数。如果没有明确地比较所有内容,有没有更快的方法来找到最大值?

我每帧执行此操作数百万次,这非常慢。

function calculateMax(a, b, c, 
                      d, e, f,
                      g, h, i){
    var max = (a > b) ? a : b;
    var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f;
    var max4 = (g > h) ? g : h;

    max = (i > max) ? i : max;
    max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max;
    max = (max4 > max) ? max4 : max;

    return max;
}

2 个答案:

答案 0 :(得分:2)

最好的方法是使用原生实现:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

console.log(Array.max([1,2,9,8,3,2,1,2,5]));  // 9

cf:https://johnresig.com/blog/fast-javascript-maxmin/

答案 1 :(得分:2)

The results seem rather disappointing after running few times,但如果有人希望在其他浏览器上做更好的测试或改进(使用SIMD instructions可能会更快)

function max1(a, b, c, d, e, f, g, h, i) {                   // shortened calculateMax
    var max  = (a > b) ? a : b; var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f; var max4 = (g > h) ? g : h;

    max = ( i   > max) ?  i   : max; max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max; max = (max4 > max) ? max4 : max;
    return max;
}

function max2(a, b, c, d, e, f, g, h, i) {
  if (a < b) a = b; if (a < c) a = c; if (a < d) a = d; if (a < e) a = e;
  if (a < f) a = f; if (a < g) a = g; if (a < h) a = h; if (a < i) a = i;
  return a;
}

//function max(a, b) { return a - ((a -= b) & (a >> 31 )); }
//function max(a, b) { return (a - b >>> 31) * b | (b - a >>> 31) * a }
function max(a, b) { return (a - b >> 31) & b | (b - a >> 31) & a }

function max3(a, b, c, d, e, f, g, h, i) {  
  return max(a, max(b, max(c, max(d, max(e, max(f, max(g, max(h, i))))))))
}

function max4(a, b, c, d, e, f, g, h, i) {
  a  =   (a - b >> 31) & b | (b - a >> 31) & a
  a  =   (a - c >> 31) & c | (c - a >> 31) & a
  a  =   (a - d >> 31) & d | (d - a >> 31) & a
  a  =   (a - e >> 31) & e | (e - a >> 31) & a
  a  =   (a - f >> 31) & f | (f - a >> 31) & a
  a  =   (a - g >> 31) & g | (g - a >> 31) & a
  a  =   (a - h >> 31) & h | (h - a >> 31) & a
  return (a - i >> 31) & i | (i - a >> 31) & a
}

var l = console.log, p = performance
var t = p.now(), m = max1(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 1, -t)
var t = p.now(), m = max2(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 2, -t)
var t = p.now(), m = max3(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 3, -t)
var t = p.now(), m = max4(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 4, -t)