What is the fastest way to sort a large(ish) array of numbers in JavaScript

前端 未结 2 932
你的背包
你的背包 2021-01-08 00:07

In my application, I need to sort large arrays (between 100,000 and 1,000,000) of random numbers.

I\'ve been using the built in array.sort(comparisonFunction)<

2条回答
  •  無奈伤痛
    2021-01-08 00:25

    There are sort implementations that consistently beat the stock .sort (V8 at least), node-timsort being one of them. Example:

    var SIZE = 1 << 20;
    
    var a = [], b = [];
    
    for(var i = 0; i < SIZE; i++) {
        var r = (Math.random() * 10000) >>> 0;
        a.push(r);
        b.push(r);
    }
    
    console.log(navigator.userAgent);
    
    console.time("timsort");
    timsort.sort(a, (x, y) => x - y);
    console.timeEnd("timsort");
    
    console.time("Array#sort");
    b.sort((x, y) => x - y);
    console.timeEnd("Array#sort");

    Here are some timings from different browsers I have around (Chakra anyone?):

    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36
    timsort: 256.120ms
    Array#sort: 341.595ms
    
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14
    timsort: 189.795ms
    Array#sort: 245.725ms
    
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0) Gecko/20100101 Firefox/51.0
    timsort: 402.230ms
    Array#sort: 187.900ms
    

    So, the FF engine is very different from Chrome/Safari.

提交回复
热议问题