5

I currently have a function that runs around 200 times.

The function look like this:

function GetB(av,bol){
var bxes=[
["11","12","13","21","22","23","31","32","33"],
["14","15","16","24","25","26","34","35","36"],
["17","18","19","27","28","29","37","38","39"],
["41","42","43","51","52","53","61","62","63"],
["44","45","46","54","55","56","64","65","66"],
["47","48","49","57","58","59","67","68","69"],
["71","72","73","81","82","83","91","92","93"],
["74","75","76","84","85","86","94","95","96"],
["77","78","79","87","88","89","97","98","99"]
];

//code
}

My first concern is that this array is slowing down everything because I think it is rewriting each time the array bxes (or something like that)

This bxes array is never modified and I wouldn't mind to make it a global.

  • Do I need to worry about the rewriting thing? (or do browsers keep track if it was ever modified, and if it wasn't it won't rewrite it)
mithril333221
  • 799
  • 2
  • 9
  • 20
  • possible duplicate of [What is JavaScript garbage collection?](http://stackoverflow.com/questions/864516/what-is-javascript-garbage-collection) – Jahan Zinedine Jan 15 '12 at 06:09

2 Answers2

3

Why wouldn't you move it outside the function? (Why risk it causing a performance issue?)

It wouldn't necessarily even have to be "global" - just in a parent scope of the function - but both the function and bxes and other code could exist in a parent function or closure...

(function(){
  var bxes = [...];
  window.GetB = function(av,bol){...};
})();
ziesemer
  • 27,712
  • 8
  • 86
  • 94
  • I remember once reading about these self-calling functions. Just a question, my onload/ready code should be outisde that or inside? – mithril333221 Jan 15 '12 at 06:14
  • Doesn't really matter - but I'd put it all inside if you don't have it inside a closure or parent function already - in an effort to [prevent global namespace pollution](http://blogger.ziesemer.com/2007/10/respecting-javascript-global-namespace.html). (Your onload/ready function may already be acting as this closure.) – ziesemer Jan 15 '12 at 06:16
3

A simple benchmark shows the answer. With the function declared as you wrote it, 5,000,000 calls takes 12.739 seconds. With the array definition moved outside the function the same loop consumes just 0.169.

Remember that this will vary according to the JavaScript engine - and so the browser - being used.

Borodin
  • 126,100
  • 9
  • 70
  • 144