I'm not sure why your tests do what they do.
But if you are going to often call Math.floor, you can use this:
var num = 9.99; var floored = ~~num;
Not that ~~ will probably not work on strings ( var num = "9.99" ), the numbers are in the 32-bit range, but negative numbers ( ~~ are rounded).
See this question for more information.
UPDATE
Here is the modified criterion
In Chrome, I get a local scope returning faster than Math.floor and the global scope. (window.mfloor) Note that I am not referring to the global mfloor with the window. syntax window. as in the original test.
So, I think your test has 2 problems (besides mixing the variable name mentioned in other answers). One of them was that you started the loop on window.mfloor, and the other - you had a local variable with the same name as the global variable (this is just an assumption).
Try the test using the jsbin link that I posted and get back to me.
here is my guideline for the lazy:
window.onload = function(){ var k = 0, i=0, n = 2000000, startTime = +(new Date); for(; i < n; ++i) k += Math.floor(9.99); var mathFloorTime = (new Date) - startTime; window.globalMfloor = Math.floor; k = i = 0; startTime = +(new Date); for(; i < n; ++i) k += globalMfloor(9.99); var globalFloorTime = (new Date) - startTime; var mfloor = Math.floor; k = i = 0; startTime = +(new Date); for(; i < n; ++i) k += mfloor(9.99); var localFloorTime = (new Date) - startTime; alert("Math.floor: " + mathFloorTime); alert("globalMfloor: " + globalFloorTime); alert("mfloor: " + localFloorTime); };β
David murdoch
source share