Nice programing

가장 빠른 JavaScript 요약

nicepro 2020. 11. 22. 20:35
반응형

가장 빠른 JavaScript 요약


JavaScript에서 배열을 요약하는 가장 빠른 방법은 무엇입니까? 빠른 검색은 몇 가지 다른 방법 으로 전환되지만 가능하면 기본 솔루션을 원합니다. 이것은 SpiderMonkey에서 실행됩니다.

내가 사용하고있는 매우 내부적 인 생각 :

var count = 0;
for(var i = 0; i < array.length; i++)
{
    count = count + array[i];
}

나는 직선 반복보다 더 나은 방법이 있다고 확신합니다.


를 사용할 수 있어야합니다 reduce.

var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);

출처

그리고 함께 화살표 기능 ES6에 도입, 심지어는 간단합니다 :

sum = array.reduce((pv, cv) => pv + cv, 0);

개량


루핑 구조를 더 빠르게 만들 수 있습니다.


   var count = 0;
   for(var i=0, n=array.length; i < n; i++) 
   { 
      count += array[i]; 
   }

이것은 array.length각 반복이 아닌 한 번 검색 합니다. 값을 캐싱하여 최적화합니다.


정말 속도를 높이고 싶다면 :


   var count=0;
   for (var i=array.length; i--;) {
     count+=array[i];
   }

이것은 while 역방향 루프와 동일합니다. 값을 캐시하고 0과 비교되므로 반복이 더 빠릅니다.

보다 완전한 비교 목록은 my JSFiddle을 참조하십시오 .
참고 : array.reduce는 끔찍하지만 Firebug Console에서는 가장 빠릅니다.


구조 비교

배열 요약을 위해 JSPerf시작했습니다 . 신속하게 구성되었으며 완전하거나 정확하다는 보장은 없지만 편집 이 필요한 이유 입니다. :)


배열을 합산하는 가장 좋은 방법을 찾는 동안 성능 테스트를 작성했습니다.

Chrome에서는 "reduce"가 훨씬 더 우수한 것 같습니다.

이게 도움이 되길 바란다

// Performance test, sum of an array
  var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var result = 0;
// Eval
  console.time("eval");
  for(var i = 0; i < 10000; i++) eval("result = (" + array.join("+") + ")");
  console.timeEnd("eval");
// Loop
  console.time("loop");
  for(var i = 0; i < 10000; i++){
    result = 0;
    for(var j = 0; j < array.length; j++){
      result += parseInt(array[j]);
    }
  }
  console.timeEnd("loop");
// Reduce
  console.time("reduce");
  for(var i = 0; i < 10000; i++) result = array.reduce(function(pv, cv) { return pv + parseInt(cv); }, 0);
  console.timeEnd("reduce");
// While
  console.time("while");
  for(var i = 0; i < 10000; i++){
    j = array.length;
    result = 0;
    while(j--) result += array[i];
  }
  console.timeEnd("while");

평가 : 5233.000ms

루프 : 255.000ms

감소 : 70.000ms

동안 : 214.000ms


아니면 악한 방법으로 할 수 있습니다.

var a = [1,2,3,4,5,6,7,8,9];

sum = eval(a.join("+"));

;)


이 테스트 에 따르면 가장 빠른 루프 는 반대의 while 루프입니다.

var i = arr.length; while (i--) { }

따라서이 코드는 얻을 수있는 가장 빠른 코드 일 수 있습니다.

Array.prototype.sum = function () {
    var total = 0;
    var i = this.length; 

    while (i--) {
        total += this[i];
    }

    return total;
}

Array.prototype.sum adds a sum method to the array class... you could easily make it a helper function instead.


For your specific case, just use the reduce method of Arrays:

var sumArray = function() {
    // Use one adding function rather than create a new one each
    // time sumArray is called
    function add(a, b) {
        return a + b;
    }

    return function(arr) {
        return arr.reduce(add);
    };
}();

alert( sumArray([2, 3, 4]) );

Based on this test (for-vs-forEach-vs-reduce) and this (loops)

I can say that:

1# Fastest: for loop

var total = 0;

for (var i = 0, n = array.length; i < n; ++i)
{
    total += array[i];
}

2# Aggregate

For you case you won't need this, but it adds a lot of flexibility.

Array.prototype.Aggregate = function(fn) {
    var current
        , length = this.length;

    if (length == 0) throw "Reduce of empty array with no initial value";

    current = this[0];

    for (var i = 1; i < length; ++i)
    {
        current = fn(current, this[i]);
    }

    return current;
};

Usage:

var total = array.Aggregate(function(a,b){ return a + b });

Inconclusive methods

Then comes forEach and reduce which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.


one of the simplest, fastest, more reusable and flexible is:

Array.prototype.sum = function () {
    for(var total = 0,l=this.length;l--;total+=this[l]); return total;
}

// usage
var array = [1,2,3,4,5,6,7,8,9,10];
array.sum()

What about summing both extremities? It would cut time in half. Like so:

1, 2, 3, 4, 5, 6, 7, 8; sum = 0

2, 3, 4, 5, 6, 7; sum = 10

3, 4, 5, 6; sum = 19

4, 5; sum = 28

sum = 37

One algorithm could be:

function sum_array(arr){
    let sum = 0,
        length = arr.length,
        half = Math.floor(length/2)

    for (i = 0; i < half; i++) {
        sum += arr[i] + arr[length - 1 - i]
    }
    if (length%2){
        sum += arr[half]
    }
    return sum
}

It performs faster when I test it on the browser with performance.now(). I think this is a better way. What do you guys think?

참고URL : https://stackoverflow.com/questions/3762589/fastest-javascript-summation

반응형