Sunday, December 6, 2009

Javascript Interpreter Optimization

Good code requires less effort for interpreter to execute. Look the following code snippet:

for(var i=0; i<count; i++){
$get('divContent').appendChild(element[i];
}

Every time of the loop requires interpreter to execute $get method to find the divContent element, that should be avoid because each time the element is the same.

var divContent = $get('divContent');
for(var i=0; i<count; i++){
divContent.appendChild(elementp[i]);
}

Above code is better because it only need the interpreter find divContent element once. It can be even better:


var divContentAppendChild = $get('divContent').appendChild;
for(var i=0;i<count;i++){
divContentAppendChild(element[i]);
}

Above code using delegate saves time for the interpreter to lookup the scope chain for the function.

Of cause we can apply the following way to append a group of elements to an exist element by assigning it's innerHtml attribute.
$get('divContent').innerHtml = strContent;

Define javascript array in two ways:
var links = ["microsoft.com", "yahoo.com", "cbc.ca"];
var strArray = new Array();
strArray.push("<div>");
strArray.push("some content");
strArray.push("/div");

No comments: