• Post Reply Bookmark Topic Watch Topic
  • New Topic

why is first version of code slower than the second ?  RSS feed

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First:

Second:





Why is the first line of code slower than the first ?!

Here is the code to test this:



Its output is:
one = 265
two = 266


Why is that ?
 
Sheriff
Posts: 4930
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change code places. Put method "two" to the top of your program, and "one" to the bottom.
See what happens then.

Also, try to separate methods to a two different programs.
 
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have a one millisecond difference, that's well within your margin of error.
Use System.nanoTime() for performance testing.
Empty loops have the potential for being optimized away.
For that many loop iterations, would 1 millisecond make a difference? Is that difference worth the possibility of making the code less readable?
You would need to run the test many times to see what the average duration is.
You would need to run one() followed by two() and also two() followed by one().
 
Lucian Whiteman
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carey Brown wrote:You have a one millisecond difference, that's well within your margin of error.


As I want to learn java, I have no margin of error.

Carey Brown wrote:
For that many loop iterations, would 1 millisecond make a difference?


Yes

Carey Brown wrote:Is that difference worth the possibility of making the code less readable?


No


Where is this difference coming from ? How can I use it in my advantage ?
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lucian Whiteman wrote:How can I use it in my advantage ?

You shouldn't even try. First, you have no proof there IS a real difference. Did you follow the suggestions people gave - reversing the order, using nano time, etc.?

Next...what possible situation do you have where one millisecond in this loop makes any difference? Considering you'll probably be doing stuff inside a loop that takes time (disk I/O, network communication, DB access...something), the millisecond here will be lost in all that processing.

It is simply NOT WORTH IT to fret over something as meaningless as this at the cost of making your code harder to read/maintain.
 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran your code multiple times, sometimes one was faster, sometimes two was faster, and sometimes they were equal. How many times did you test your code?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!