Re: Simple loop optimization

From: Russ Tennant (news_at_russtennant.com)
Date: 02/08/04


Date: Sun, 08 Feb 2004 00:20:11 -0600

Chris wrote:

> "mrTriffid" <mr_triffid@etoast.com> wrote in message
> news:a2aa6dc9.0402041353.535e1cfb@posting.google.com...
>> Hi,
>>
>> I'm interested in finding out something that's been bugging me for a
>> while now; does it make sense to optimize the following (idealised)
>> for-loop
>> for (int i = 0; i < foo.getBar(); i++)
>> into something like
>> for (int i = foo.getBar()-1; i >= 0; i--)
>> (assuming foo.getBar() doesn't change for the duration of the loop)?
>>
>> In the first case, foo.getBar() is (theoretically) evaluated many
>> times, but only once in the second.
>>
>> Ignoring the fact that the Java spec probably says nothing about such
>> optimizations, does it make sense to assume that (say) the vanilla Sun
>> JDK compiler would spot this, and would optimize the first loop to be
>> as good as the second?
>
> For most purposes, the difference in speed is not significant. I'd only
> optimize if absolutely necessary.
>
> That having been said, I often do something like this:
>
> final int count = foo.getBar();
> for (int i = 0; i < count; i++) {
> }

How about:

for (int i = 0, bound = foo.getBar(); i < bound; i++) {
}

This way the variable isn't too widely scoped if not needed.

--
Russ Tennant
news@russtennant.com


Relevant Pages

  • Simple loop optimization
    ... I'm interested in finding out something that's been bugging me for a ... does it make sense to assume that the vanilla Sun ... and would optimize the first loop to be ...
    (comp.lang.java.programmer)
  • Re: Simple loop optimization
    ... "mrTriffid" wrote in message ... > I'm interested in finding out something that's been bugging me for a ... > JDK compiler would spot this, and would optimize the first loop to be ...
    (comp.lang.java.programmer)
  • Re: how to move into a recordset?
    ... chris wrote: ... Suppose i need to know the number of records before showing them. ... first loop, i get the number of records, but I think the pointer in the ... Is there a way to put the pointer to the beginning? ...
    (alt.php)
  • Re: choose a correct C#
    ... "Chris M. Thomasson" wrote in message ... It may be patched to free excessive cached nodes. ... thing that is bugging me is how to handle the case when a thread quits with outstanding allocations... ...
    (comp.programming.threads)
  • Re: Pinbrawl player needed to complete TEAM PinFooties !
    ... Koz is bugging me to get this ... Can I count on you Chris? ... Pinlicious (...there is no spoon.) ...
    (rec.games.pinball)