|No such thing as a small change|
Re: Question about curious performance of if...elsif blockby BrowserUk (Pope)
|on Jan 16, 2012 at 18:59 UTC||Need Help??|
I would have expected the difference between running this script with the return statement commented out and not commented out to be on the order of a second or less yet it's actually over 5 seconds. This seems like a huge difference and I'd like to know if anyone can tell me why and more importantly if there's a way to improve things.
The reason it takes so long -- although in my tests of your sample code show the difference to be far less than 5 seconds -- is because for the vast majority of the cases, $i = 10 through 1,440 (or 1,000,000), you are performing all nine comparisons before returning.
The simple solution is to avoid doing those comparisons 99% (or 99.99999^) of the time:
On my system this consistently runs even faster than your test() sub with the unconditional return (test2 below):
Update: Also, if your if/else cascade is bigger than 9, then you might consider using a dispatch table:
This runs pretty nearly exactly the same speed as test3 above when the number of blocks is low (9 in this case), but once you get to around 20 or so, it starts to win more substantially.
And if your cases are less amenable to using an array, then you can use a hash instead.
But do construct the dispatch table outside the subroutine. Do it (every time) inside teh sub and it will slow to a crawl.
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.