math vs loop

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var values = [123, 123123123, 45367876,  35433, 8, 234536576578, 34242, 2341, 1212443, 234234567, 9874765]
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
math
var i;

for (i = 0; i < values.length; i++) {
  var j = Math.floor(Math.log(values[i]) / Math.log(1024));
  (values[i] / Math.pow(1024, i)).toFixed(2) + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
}
pending…
loop
var i, j, units = [[1099511627776, 'TiB'], [1073741824, 'GiB'], [1048576, 'MiB'], [1024, 'KiB'], [0, 'B']]

for (i = 0; i < values.length; i++) {
  for (j = 0; j < units.length; j++) {
    if (values[i] >= units[j][0]) {
      (values[i] / units[j][0]).toFixed(2) + ' ' + units[j][1];
      break;
    }
  }
}
pending…

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

Compare results of other browsers

0 comments

Add a comment