Skip to content

Instantly share code, notes, and snippets.

@gfarrell
Last active June 29, 2017 15:54
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 gfarrell/4b33ea181ac3fc15c1d810c28565dfd4 to your computer and use it in GitHub Desktop.
Save gfarrell/4b33ea181ac3fc15c1d810c28565dfd4 to your computer and use it in GitHub Desktop.
Sorting performance: Strings VS. Numbers
~/sandbox > node strings-vs-ints.js 1000000 32
Sorting 1000000 numbers of magnitude 10^32
Sorting 1000000 strings of length 32
Numbers: 461
Strings: 1445
~/sandbox > node strings-vs-ints.js 1000000 32
Sorting 1000000 numbers of magnitude 10^32
Sorting 1000000 strings of length 32
Numbers: 494
Strings: 1500
~/sandbox > node strings-vs-ints.js 1000000 16
Sorting 1000000 numbers of magnitude 10^16
Sorting 1000000 strings of length 16
Numbers: 493
Strings: 1468
~/sandbox > node strings-vs-ints.js 10000 16
Sorting 10000 numbers of magnitude 10^16
Sorting 10000 strings of length 16
Numbers: 8
Strings: 8
~/sandbox > node strings-vs-ints.js 100000 16
Sorting 100000 numbers of magnitude 10^16
Sorting 100000 strings of length 16
Numbers: 51
Strings: 100
"use strict";
const CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjijklmnopqrstuvwxyz0123456789:.";
function generateString(L) {
const chars = [];
while(chars.length < L) {
chars.push(CHARSET[Math.floor(Math.random() * CHARSET.length)]);
}
return chars.join("");
}
function generateNumber(L) {
return Math.floor(Math.random() * Math.pow(10, (L - 1))) + Math.pow(10, L - 1);
}
function generateList(generator, L, N) {
const elements = [];
while(elements.length < N) {
elements.push(generator.call(null, L));
}
return elements;
}
function now() {
return Date.now();
}
function getTime(baseTime) {
return now() - baseTime;
}
function main(count, size) {
console.log(`Sorting ${count} numbers of magnitude 10^${size}`);
const numbers = generateList(generateNumber, size, count);
const numBaseTime = now();
numbers.sort((a, b) => (a - b)); // force JS to sort as numbers not strings
const numTime = getTime(numBaseTime);
console.log(`Sorting ${count} strings of length ${size}`);
const strings = generateList(generateString, size, count);
const strBaseTime = now();
strings.sort();
const strTime = getTime(strBaseTime);
console.log(`Numbers: ${numTime}\nStrings: ${strTime}`);
}
main(process.argv[2], process.argv[3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment