~~ vs >> vs parseInt (bitwise operators) (v8)

Revision 8 of this benchmark created on


Description

Test performance of different methods to convert a number into an integer.

Using a loop inside the checks to make sure IE 7-8 don't hit the code execution limit and also to make sure the JIT isn't being smart and pre-calculating the values (that's why I'm incrementing the result and not simply re-assigning it).

Preparation HTML

<script>
  var items = [];
  var n = 0;
  var result = 0;
  
  while(n++ < 100){
    items[n] = n + Math.random();
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
NOT
n = items.length;
result = 0;
while(--n){
  result += ~~ items[n];
}
ready
SHIFT
n = items.length;
result = 0;
while(--n){
  result += items[n] >> 0;
}
ready
parseInt
n = items.length;
result = 0;
while(--n){
  result += parseInt(items[n], 10);
}
ready
floor
n = items.length;
result = 0;
while(--n){
  result += Math.floor(items[n]);
}
ready
AND
n = items.length;
result = 0;
while(--n){
  result += items[n] | 0;
}
ready
toFixed
n = items.length;
result = 0;
while(--n){
  result += items[n].toFixed(); 
}
ready
toPrecision(1)
n = items.length;
result = 0;
while(--n){
  result += items[n].toPrecision(1);
}
ready
modulo
n = items.length;
result = 0;
while(--n){
  result += items[n] - items[n] % 1;
}
ready
XOR
n = items.length;
result = 0;
while(--n){
  result += items[n] ^ 0;
}
ready
parseFloat
n = items.length;
result = 0;
while(--n){
  result += parseFloat(items[n], 10);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.