realbasic-nug
[Top] [All Lists]

Re: For/next and array ubounds: optimising performance

To: REALbasic NUG <realbasic-nug at lists dot realsoftware dot com>
Subject: Re: For/next and array ubounds: optimising performance
From: James Sentman <james at sentman dot com>
Date: Thu, 17 May 2007 10:30:58 -0400
Delivered-to: listarchive at realsoftware dot com
Delivered-to: realbasic-nug at lists dot realsoftware dot com
References: <BAY107-DAV1220614F6DAB795C0116B093330 at phx dot gbl>
On May 17, 2007, at 9:21 AM, Daniel Stenning wrote:

> fyi:  38 seconds vs 43 seconds.
>
> Not a lot but using a local var is still consistently faster.
>
>
> On 17/5/07 14:14, "Daniel Stenning" <d0stenning at msn dot com> wrote:
>
>>
>> Now I just did some timings, and it seems that there is a slight  
>> ( not great
>> ) performance advantage with using a local variable.
>
> Regards,


The problem is that you're evaluating the ubound everytime you go  
around the loop. The higher the ubound value the more times you'll  
have to evaluate it and the slower your loop will run.

There is also a very slight penalty to declaring the variable inside  
the loop, I just ran that test yesterday.

Anything you do more than once you need to be very careful about, any  
slight overhead for a object lookup or a function call will add up  
significantly the more you have to do it. If you only need to call  
something once it doesn't really matter, but in a loop in can make a  
huge difference in performance. Anything you repeatedly need to  
compare against or use should be in a local variable and when  
possible and when it makes sense for code readability you should not  
redeclare any variables inside the loop.

dim i, count as integer

count = ubound( SomeArray)
for i = 0 to count
   //do something
next

is always and without exception going to be faster than

for i as integer = 0 to ubound( SomeArray)
//
next

cause in the first example you're only calculating the ubound value  
once. So get over thinking that the other is better, it uses fewer  
lines of code, but is more complex and runs slower, so it's only an  
illusion of betterness ;)

In addition object lookups and accesses are non-trivial so anything  
else you can pull into a local variable for comparison helps a LOT too.


-James
_______________________________________________
Unsubscribe or switch delivery mode:
<http://www.realsoftware.com/support/listmanager/>

Search the archives:
<http://support.realsoftware.com/listarchives/lists.html>


<Prev in Thread] Current Thread [Next in Thread>