Win a copy of Spring Boot in Practice this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Math and Loops

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My question is about the condition a for statement.
I'm assuming that the condition is re-evaluated at each loop iteration. If the condition contains a mathematical function and the parameters do not change at each iteration, is the math operation re-evaluated as well.
In other words, is it better to do the calculation outside the loop for performance sake(1) than having calculation done in the for statement(2) ?
ex
(1):
nbLeftOff = x * y ;
for ( int j = 0 ; j < nbLeftOff ; j++ )
(2):
for ( int j = 0 ; j < x * y ; j++ )

 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi JeanMichel,
JLS §14.13 says "if an expression is present, it is evaluated". This would happen with each iteration so it's probably 'cheaper' to use method 1 vs method 2.
Hope that helps
------------------

Jane Griscti
Sun Certified Java 2 Programmer
"When ideas fail, words come in very handy" -- Goethe
 
Trailboss
Posts: 23463
IntelliJ IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would use your technique (1) in most cases.
 
JeanMichel Hanquet
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, that's what I thought.
Now, talking about Assignment 1.1, would it be more efficient/faster/cheaper to
1. build 1 big string and use System.out.println( myBigString ) and the end of the loop to print it out on the screen
2. print out the words as I go through the loop invoking System.out.println( myWordToPrint ) each time.
It seems to me that printing on the screen is more CPU consuming. Up to a point where String manipulation becomes more of an issue.
Jm
 
reply
    Bookmark Topic Watch Topic
  • New Topic