Optimization Monday — Part VIII: use function pointers
Optimization Monday February 4th, 2008Let 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. :-)
February 4th, 2008 at 22:16
Always a good tip for newbies. And variants – a system in qooxdoo – even can improve this one again. ;)
February 5th, 2008 at 09:18
Hi Jonny,
looking at the sample, I would strongly suggest using the factory or the strategy pattern ;-)
Cheerio,
Golo
February 5th, 2008 at 10:27
Sebastian, that is where I got the idea from…
Golo, you are so right – but my intention is to keep this examples as short and simple as possible. ;-)