Skip to content

Instantly share code, notes, and snippets.

@sturmer
Last active January 25, 2018 12:26
Show Gist options
  • Select an option

  • Save sturmer/443f3ea384ff745af7cd6ef867ddbccd to your computer and use it in GitHub Desktop.

Select an option

Save sturmer/443f3ea384ff745af7cd6ef867ddbccd to your computer and use it in GitHub Desktop.
Initialize variable without callback (but give up const-ness)
#!/usr/local/bin/node
// Test: Is it faster to initialize a const via callback, or to use let and then an if statement?
// Solution 2: no callback (but also, no const)
const TIMES = 1e6;
const time = process.hrtime(); // returns [seconds, nanoseconds]
for (let i = 0; i < TIMES; i++) {
let x = null;
// Imagine some more processing here...
if (2 + 1 === 4) {
x = "impossible";
} else {
x = "OK";
}
}
setTimeout(() => {
const diff = process.hrtime(time);
console.log(`Benchmark took: ${diff[0]} s ${diff[1] / 1e6} ms`);
}, 0);
// Result:
// Benchmark took: 0 s 4.782179 ms
#!/usr/local/bin/node
// Test: Is it faster to initialize a const via callback, or to use let and then an if statement?
// Solution 1: Via callback
const TIMES = 1e6;
const time = process.hrtime(); // returns [seconds, nanoseconds]
for (let i = 0; i < TIMES; i++) {
const x = () => {
if (2 + 1 === 4) {
return "impossible";
} else {
return "OK";
}
};
}
// Doing this instead of just storing diff and printing shaves off ~10ms. Must have something to do with
// how the node loop works.
setTimeout(() => {
const diff = process.hrtime(time);
console.log(`Benchmark took: ${diff[0]} s ${diff[1] / 1e6} ms`);
}, 0);
// Result:
// Benchmark took: 0 s 18.443828 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment