Randy said:
Thomas 'PointedEars' Lahn said the following on 3/8/2006 7:09 PM:
If a direct call to Math.floor is compared with the use of bitwise OR
wrapped in a function (as per Randy's test), then your doubts are
confirmed - but that's not what I was suggesting.
The OP posted a function called round1() that wrapped Math.floor. I was
suggesting that the entire function be replaced, not that round1()
should call toFloor().
Nor did I say 'It is claimed' for no reason:
"Math.ceil/floor Vs parseInt Vs plus/minus"
<URL:
http://groups.google.co.uk/group/co...nt+Vs+plus/minus&rnum=1&#doc_56a3f10f32a8b480>
Richard is correct, bitwise OR seems to be faster than Math.floor at
least in IE and Firefox, see below.
It's easy enough to test:
function toFloor(num){ return num|0; }
iterations = 1000000;
var begin1 = new Date();
for (i=0;i<iterations;i++){
var k = toFloor(3.45);
}
var end1 = new Date();
var totalTime1 = end1 - begin1;
document.write('toFloor() took ' + totalTime1 + ' milliseconds<br>')
var begin2 = new Date();
for (i=0;i<iterations;i++){
var k = Math.floor(3.45);
}
var end2 = new Date();
var totalTime2 = end2 - begin2;
document.write('Math.floor() took ' + totalTime2 + ' milliseconds<br>')
The result of which is to show that a direct call to Math.floor is
faster than '|' wrapped in a function.
But the test is unfair - to make it even, either Math.floor() should be
wrapped in a function, as the OP had done, or '|' should be called
directly. If:
var k = toFloor(3.45);
is replaced with:
var k = 3.45 | 0;
then Math.floor and '|' are nearly identical for speed.
But the test is still flawed, the same number is being used
consistently. Replace 3.45 with Math.random()*5 - now '|' wins by a
small margin in Firefox and a very large margin in IE.
QED.