Skip to content

Instantly share code, notes, and snippets.

@ifraixedes
Last active August 29, 2015 14:03
Show Gist options
  • Save ifraixedes/f0d41143c60ceb8c7c58 to your computer and use it in GitHub Desktop.
Save ifraixedes/f0d41143c60ceb8c7c58 to your computer and use it in GitHub Desktop.
It contains some cases where a nice syntax is used in expense of performance
'use strict';
var NUM_ITERATIONS = 99999999;
var i, tmp, tmp2, initTime, stopTime;
// Iteration using for loop assigning the value always
initTime = Date.now();
for (i = 0; i < NUM_ITERATIONS; i++) {
tmp = (i % 2) || tmp;
}
stopTime = Date.now();
console.log('Iterate using for loop by assigning the value when have to change and not: %s ms', stopTime - initTime);
// Iterate using a if condition to check if the value have to change
initTime = Date.now();
for (i = 0; i < NUM_ITERATIONS; i++) {
tmp2 = (i % 2);
if (tmp2 !== 0) {
tmp = tmp2;
}
}
stopTime = Date.now();
console.log('Iterate using for loop by wrapping the value calculation in a boring if conditional: %s ms', stopTime - initTime);
function checkMod (value) {
var tmp = (value % 2);
if (tmp !== 0) {
return tmp;
} else {
return value;
}
}
initTime = Date.now();
for (i = 0; i < NUM_ITERATIONS; i++) {
tmp = checkMod(i);
}
stopTime = Date.now();
console.log('Iterate using for loop by wrapping the value calculation in a function called for each iteration: %s ms', stopTime - initTime)
// Iterate using for loop by wrapping the value calcualtion in a function declared on each iteration
initTime = Date.now();
for (i = 0; i < NUM_ITERATIONS; i++) {
tmp = (function (value) {
var tmp = (value % 2);
if (tmp !== 0) {
return tmp;
} else {
return value;
}
}(i));
}
stopTime = Date.now();
console.log('Iterate using for loop by wrapping the value calculation in a function declared on each iteration: %s ms', stopTime - initTime);
// Using conditional if/else
initTime = Date.now();
for (i = 0; i < NUM_ITERATIONS; i++) {
tmp = 0.5 - Math.random();
if (tmp < 0) {
tmp = 0;
}
}
stopTime = Date.now();
console.log('Checking value and assigning one when a condition is not fulfilled: %s ms', stopTime - initTime);
// Using conditional Math.max()
initTime = Date.now();
for (i = 0; i < NUM_ITERATIONS; i++) {
tmp = Math.max(0.5 - Math.random(), 0);
}
stopTime = Date.now();
console.log('Checking value and assigning one using Math.max: %s ms', stopTime - initTime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment