Monday, July 14, 2008

The memoization

The memoization is a very efficiency way when you want some heavy computation to be done only once at first time. Let check the ajax creating an XhrObject example createXhrObject: function() { // Factory method.
var methods = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
for(var i = 0, len = methods.length; i <>
try {
methods[i]();
}
catch(e) {
continue;
}
// If we reach this point, method[i] worked.
this.createXhrObject = methods[i]; // Memoize the method.
return methods[i];
}
The object creation will be heavily checking the computability of each browser. But it will done only at the first time, the function createXhrObject will replace itself with the creation method once found the browser compatibility.

No comments: