Skip to content

Instantly share code, notes, and snippets.

@eight04
Created July 20, 2015 10:40
Show Gist options
  • Save eight04/9d7d97f6196017fac155 to your computer and use it in GitHub Desktop.
Save eight04/9d7d97f6196017fac155 to your computer and use it in GitHub Desktop.
[JavaScript] Will duplicate items affect the performance of Array.sort?
"size=1, range=1: 0"
"count=0"
"size=10, range=1: 0"
"count=9"
"size=100, range=1: 0"
"count=99"
"size=1000, range=1: 1"
"count=999"
"size=10000, range=1: 2"
"count=9999"
"size=100000, range=1: 21"
"count=99999"
"size=1000000, range=1: 257"
"count=999999"
"size=1, range=1000: 0"
"count=0"
"size=10, range=1000: 0"
"count=24"
"size=100, range=1000: 0"
"count=648"
"size=1000, range=1000: 1"
"count=9338"
"size=10000, range=1000: 23"
"count=125565"
"size=100000, range=1000: 306"
"count=1655291"
"size=1000000, range=1000: 3929"
"count=19372335"
size=1, range=1: 20
count=0
size=10, range=1: 1
count=9
size=100, range=1: 0
count=99
size=1000, range=1: 0
count=999
size=10000, range=1: 4
count=10048
size=100000, range=1: 6
count=100498
size=1000000, range=1: 24
count=1005022
size=1, range=1000: 0
count=0
size=10, range=1000: 0
count=25
size=100, range=1000: 0
count=611
size=1000, range=1000: 2
count=8910
size=10000, range=1000: 4
count=101079
size=100000, range=1000: 21
count=996053
size=1000000, range=1000: 273
count=9831909
function createArr(size, range){
var arr = [];
while (size--) {
arr.push(Math.floor(Math.random() * range));
}
return arr;
}
var benchmark = function(){
var ts, message;
function start(text) {
ts = Date.now();
message = text;
}
function stop() {
console.log(message + ": " + (Date.now() - ts));
}
return {
start: start,
stop: stop
};
}();
function test(range, size) {
var arr = createArr(size, range),
count = 0;
benchmark.start("size=" + size + ", range=" + range);
arr.sort(function(a, b){
count++;
return a - b;
});
benchmark.stop();
console.log("count=" + count);
}
[1, 1000].forEach(function(range){
[1, 10, 100, 1000, 10000, 100000, 1000000].forEach(function(size){
test(range, size);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment