Skip to content

Instantly share code, notes, and snippets.

@cchang62
Last active March 1, 2023 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cchang62/cbfdb10408be3d25f03da99bab1c2c2c to your computer and use it in GitHub Desktop.
Save cchang62/cbfdb10408be3d25f03da99bab1c2c2c to your computer and use it in GitHub Desktop.
js sort speed test, length < 30000 elements

In web console tab, execute the following script to test the sorting speed with < 30k elements

// load js file via URL
function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL
   
    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}
dynamicallyLoadScript("https://rawgithub.com/mziccard/node-timsort/master/build/timsort.js")

// generate a big array and test the sorting
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");

/*
SIZE: 1048576
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36
VM417:15 timsort: 189.770263671875 ms
VM417:19 Array#sort: 280.050048828125 ms
*/

Reference

Import js lib sort large array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment