Re: Simple loop optimization
From: Russ Tennant (news_at_russtennant.com)
Date: 02/08/04
- Next message: Dale: "Struts Tokens - Newbie"
- Previous message: Justin Mencl: "Re: how can I put jsp files with html files"
- In reply to: Chris: "Re: Simple loop optimization"
- Next in thread: Tony Morris: "Re: Simple loop optimization"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Dale: "Struts Tokens - Newbie"
- Previous message: Justin Mencl: "Re: how can I put jsp files with html files"
- In reply to: Chris: "Re: Simple loop optimization"
- Next in thread: Tony Morris: "Re: Simple loop optimization"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|