Benchmark - Math.sqrt distance calculation VS Tile method

by Michael Prosser

HTML

<h1>toFixed(2) calculation VS Custom method</h1>
<h3 id="xfaster">Roughly 28.1x faster</h3>
<p id="output"></p>
<p id="averages"></p>

CSS

body{
  font-family: helvetica, serif;
}
#output{
  max-height: 100px;
  overflow: auto;
  font-size: 10px;
  border: solid 1px #ccc;
  padding: 10px;
}

JavaScript

var scene = {
	name: "MY SCENE"
};

var running1 = 0;
var running2 = 0;

function method1(position,rotation,d){
	
  	var t = {};

		t.r = rotation;
		
		t.p.x = position.x;
		t.p.y = position.y;
		t.p.z = position.z;
		
		if(!t.r.x){ t.r.x = 0.0000000000001; }
		
		t.p.z += Math.cos(t.r.y) * d;
		t.p.x += Math.sin(t.r.y) * d;
		t.p.y += Math.tan(t.r.x) * d;

		t.dis = t.distance(t.p, position)/d;

		d = d/t.dis;

		position.z += Math.cos(t.r.y) * d;
		position.x += Math.sin(t.r.y) * d;
		position.y += Math.tan(t.r.x) * d;
		
		return position;
    
}

function method2(n){

		return n*n;
   
}


var output = document.getElementById('output');
var averages = document.getElementById('averages');

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            //console.log('Timer:', name, 'finished in', time, 'ms');
            output.innerHTML += 'Timer: ' + name + '<br />finished in ' + time + ' ms<br />';
            
        },
        time: function() {
            var end  = new Date();
            return end.getTime() - start.getTime();
            
        }
    }
};

var count = 1000000;

var samples = 20;

var objPosition = { x: 0, y: 0, z: 0 };
var objRotation = { x: 0, y: 0, z: 0 };


for(var j=0;j<samples;j++){

  var t = timer('toFixed Method Timer');
  // code to benchmark

  for(var i=0;i<count;i++){

   method1(objPosition,0,1);

  }

  //////////////////////////////////////////////////////
  t.stop(); // prints the time elapsed to the js console
  running1 += t.time();


  var t = timer('Custom Method Timer');
  // code to benchmark

  for(var i=0;i<count;i++){

    method2(320.19282191);

  }

  //////////////////////////////////////////////////////
  t.stop(); // prints the time elapsed to the js console
  running2 += t.time();
  
  output.innerHTML += '<hr />';

}

var xFaster =...