Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should heavy variables go outside functions?

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)
like image 397
mithril333221 Avatar asked Jan 15 '12 06:01

mithril333221


2 Answers

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){...};
})();
like image 75
ziesemer Avatar answered Oct 23 '22 06:10

ziesemer


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.

like image 24
Borodin Avatar answered Oct 23 '22 08:10

Borodin