Sorting performance: Strings VS. Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
~/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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