I'm currently writing a small framework to test the speed of JavaScript functions. When I repeatedly call the same methods with the same parameter, it gives me strange results:
Function Execution Time
isEvenBitwise 38.00000000046566
isEvenModulo 38.00000000046566
isEvenPointless 38.00000000046566
Here are my functions:
var myFunctions =
{
isEvenBitwise: function(number)
{
return !(number & 1);
},
isEvenModulo: function(number)
{
return (number % 2 == 0);
},
isEvenPointless: function(number)
{
return 1;
}
}
The code that runs the functions:
PerformanceTest.prototype.measureTime = function()
{
for (var indexTests = 0; indexTests < this.testCount; indexTests++)
{
var results = [];
for (var currentFunction in this.functions) {
var contextFunction = this.functions[currentFunction];
var startTime = performance.now();
for (var i = 0; i < this.iterationsPerTest; i++)
{
var heh = contextFunction.apply(this, arguments)
}
var executionTime = performance.now() - startTime;
var result = {};
result.testName = currentFunction;
result.executionTime = executionTime;
results.push(result);
}
this.testResults.push(results);
}
}
Does the JavaScript interpreter cache/optimize my code? If so, how does it work? Or is there anything else happening I'm not aware of?
Edit: This seems to occur only in chrome, firefox works just fine with these results:
Function Execution Time
isEvenBitwise 9.652258097220447
isEvenModulo 37.546061799704376
isEvenPointless 8.512472488871936