Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jeanlucaslima
Last active May 5, 2017 05:42
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 jeanlucaslima/04144258d421177f21c41f26b14aa607 to your computer and use it in GitHub Desktop.
Save jeanlucaslima/04144258d421177f21c41f26b14aa607 to your computer and use it in GitHub Desktop.
JS Perf notes
// Estranho bug de performance encontrado por [andreasgal](https://github.com/andreasgal)
//
// Comportamento esperado: foo() e bar() terem ao menos performance similar
// Comportamento observado: foo() tem performance diferente que bar() dependendo da máquina
//
// A única diferença entre foo() e bar() é a ordem de declaração dos valores dentro do vetor
// Não sei explicar o motivo desse comportamento
var A = [];
function foo() {
var J = [124, 564, 456, 1000];
for (var i = 0; i < 5000000; i++) {
A[J[i % 4]] = i;
}
}
var B = [];
function bar() {
var K = [1000, 124, 564, 456];
for (var j = 0; j < 5000000; j++) {
B[K[j % 4]] = j;
}
}
var perf_foo_t0 = performance.now();
foo();
var perf_foo_t1 = performance.now();
var perf_bar_t0 = performance.now();
bar();
var perf_bar_t1 = performance.now();
console.log("Call to bar took " + (perf_bar_t1 - perf_bar_t0) + " milliseconds.");
console.log("Call to foo took " + (perf_foo_t1 - perf_foo_t0) + " milliseconds.");
console.log("foo was " + (perf_foo_t1 - perf_foo_t0)/(perf_bar_t1 - perf_bar_t0) + " times faster than bar.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment