Skip to content

Instantly share code, notes, and snippets.

@neonfuz
Created December 18, 2023 22:21
Show Gist options
  • Save neonfuz/72caceaaf92898b52d544d0b21801d06 to your computer and use it in GitHub Desktop.
Save neonfuz/72caceaaf92898b52d544d0b21801d06 to your computer and use it in GitHub Desktop.
moveZeroes benchmark
const fs = require('node:fs');
const moveZeroes = (nums) => {
let write = 0;
for (let read = 0; read < nums.length; ++read)
if (nums[read] !== 0)
nums[write++] = nums[read];
for (; write < nums.length; ++write)
nums[write] = 0;
return nums;
}
const moveZeroes_ = (nums) => {
return nums.sort( (a, b) => {
return ( a == 0 ) || -( b == 0);
});
}
try {
const data = fs.readFileSync('./input.txt', 'utf8');
const numbers = data.split('\n').map(Number);
console.time();
moveZeroes(numbers);
console.timeEnd();
console.time();
moveZeroes_(numbers);
console.timeEnd();
} catch (err) {
console.error(err);
}
// Output:
//
// $ node writeZeros.js
// default: 11.923ms
// default: 48.693ms
//
// Conclusion: version which uses built in array.sort is 4x slower.
@neonfuz
Copy link
Author

neonfuz commented Dec 18, 2023

input generated with:
echo "$(for n in $(seq 1 1000000); do echo 0; done; seq 1 1000000)" | shuf | tee input.txt

ran on apple m1 pro

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