By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,988 Members | 1,367 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,988 IT Pros & Developers. It's quick & easy.

compiler optimization

P: n/a
i've asked a similar question to this in the past, but the example i gave
was not good enough i think to warrant any good answers... so i've come up
with another example that should be clear.

consider a loop that adds some values from an array of doubles x... such
as (where "a" is a constant value):

for(int i = 0; i < x.length; i++)
result += (x[i] - a) / x.length;

now, one can also obviously do:

for(int i = 0; i < x.length; i++)
result += (x[i] - a);
result = result / x.length;

if the code is executed directly as it is written, the second version can
be far more efficient (only one division, vs x.length divisions)... and
let us assume that precision is not a direct concern at the moment.

does anyone know if the java compiler will attempt to see this
optimization and make the appropriate change if the code is given as it is
in the first example?

thanks much,

murat
--
Murat Tasan
mx**@po.cwru.edu
ta***@eecs.cwru.edu
mu*********@cwru.edu
http://genomics.cwru.edu

Jul 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Murat Tasan" <ta***@eecs.cwru.edu> wrote in message
news:Pine.SOL.4.53.0402222133280.27212@homer...
i've asked a similar question to this in the past, but the example i gave
was not good enough i think to warrant any good answers... so i've come up
with another example that should be clear.

consider a loop that adds some values from an array of doubles x... such
as (where "a" is a constant value):

for(int i = 0; i < x.length; i++)
result += (x[i] - a) / x.length;

now, one can also obviously do:

for(int i = 0; i < x.length; i++)
result += (x[i] - a);
result = result / x.length;

if the code is executed directly as it is written, the second version can
be far more efficient (only one division, vs x.length divisions)... and
let us assume that precision is not a direct concern at the moment.

does anyone know if the java compiler will attempt to see this
optimization and make the appropriate change if the code is given as it is
in the first example?

thanks much,

murat
--
Murat Tasan
mx**@po.cwru.edu
ta***@eecs.cwru.edu
mu*********@cwru.edu
http://genomics.cwru.edu


No, Java compilers will only optimize code in ways that will not influence
the result. Doing multiple divisions will result in a different result than
one division considering rounding etc. You will have to do that yourself.

Silvio Bierman
Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.