Benchmark - Math.sqrt distance calculation VS Tile method

by Michael Prosser

HTML

<h1>TerrainCaster distance calculation VS Tile method</h1>
<h3 id="xfaster">Roughly 2.3x - 2.5x 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 distance(p1,p2){

	return Math.sqrt(Math.pow(p2.x-p1.x,2) + Math.pow(p2.z-p1.z,2));

}

var grounds = [
	{
  	position: {
    	x: -100,
      y: 0,
      z: -100
    }
  },
  {
  	position: {
    	x: 0,
      y: 0,
      z: -100
    }
  },
  {
  	position: {
    	x: 100,
      y: 0,
      z: -100
    }
  },
  {
  	position: {
    	x: -100,
      y: 0,
      z: 0
    }
  },
  {
  	position: {
    	x: 0,
      y: 0,
      z: 0
    }
  },
  {
  	position: {
    	x: 100,
      y: 0,
      z: 0
    }
  },
  {
  	position: {
    	x: -100,
      y: 0,
      z: 100
    }
  },
  {
  	position: {
    	x: 0,
      y: 0,
      z: 100
    }
  },
  {
  	position: {
    	x: 100,
      y: 0,
      z: 100
    }
  }
]

var LOD = 80;

function method1(position){

		var closest = 100000;
		var d;
		var ground;
		var gl = grounds.length;
		
		for(var i=0;i<gl;i++){
			
			d = distance(position,grounds[i].position);
			
			if(d <= LOD){
				
				grounds[i].alwaysSelectAsActiveMesh = true;
					
			} else {
				
				grounds[i].alwaysSelectAsActiveMesh = false;
				
			}
			
			if(d < closest){
				
				closest = d;
				ground = grounds[i];
				
			}
			
		}
    
    
		
		return ground;

}

var gridX = 3;
var gridZ = 3;

function method2(position){

		var gl = grounds.length;
		
		for(var i=0;i<gl;i++){
			
      if((position.x >= grounds[i].position.x-50) && (position.x <= grounds[i].position.x+50)){
      
      	if((position.z >= grounds[i].position.z-50) && (position.z <= grounds[i].position.z+50)){
        
        	// get the grounds around the selection to activate them and deactivate the others
          // we know the center tile
          
          for(var ii=0;ii<gl;ii++){
          
              if((grounds[ii].position.x >= grounds[i].position.x-LOD) && (grounds[ii].position.x <= grounds[i].position.x-LOD)){

          			 if((grounds[ii].position.z >= grounds[i].position.z-LOD) &&...