Optimization Monday — Part VIII: use function pointers
Optimization Monday 3 Comments »Let us assume that you have a function which will execute different code based on conditions which do not change during runtime (e.g. the rendering engine of the user agent).
function doStuff(){ if(userAgent == "internetexplorer"){ // ... }else if(userAgent == "firefox"){ // .. }else if(userAgent == "webkit"){ // .. }else if(userAgent == "opera"){ // .. }else{ // .. } }
Each time the function is called the string comparisons have to be done, even if the value for userAgent will not change at all.
To optimize this situation assign the actual function code to a variable named doStuff:
if(userAgent == "internetexplorer"){ doStuff = function(){ /* .. */ }; }else if(userAgent == "firefox"){ doStuff = function(){ /* .. */ }; }else if(userAgent == "webkit"){ doStuff = function(){ /* .. */ }; }else if(userAgent == "opera"){ doStuff = function(){ /* .. */ }; }else{ doStuff = function(){ /* .. */ }; }
After this no more string comparisons are needed. :-)