• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

which one is faster in java?

 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all
my code is


//first code
1. for(int i = 100000; i > 0; i--) {}
//second code
2. for(int i = 1; i < 100000; i++) {}
and
//third code
1. Math.max(a,b);
//fourth code
2. (a>b)?a:b;
out of this two pair codes which one is faster and why?
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what were the results of your tests?
 
Anto Telvin
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to know how i can find that which one is faster ? i encountered this question in an online test .i have no idea how to find which one is faster
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you know the time an operation starts and you knoe the time it ends, you can work out the duration. See the methods in ths java.lang.System class
 
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are methods in the System class which give the computer clock setting, so you use them before and after. Remember your latter pair of statements will only take a microsecond or so to process.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
. . . And you do realise the first two loops are not equivalent to each other, nor reversed forms of each other?
[ October 11, 2008: Message edited by: Campbell Ritchie ]
 
Anto Telvin
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thankq
 
Rancher
Posts: 280
VI Editor C++ Debian
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Campbell Ritchie:
. . . And you do realise the first two loops are not equivalent to each other, nor reversed forms of each other?

[ October 11, 2008: Message edited by: Campbell Ritchie ]



Am afraid I don't.

I see them as both do-nothing loops (i.e., 'equivalent') that essentially increment/decrement (in that sense 'reversed forms') an integer 100000 times. In both cases, this integer is no longer available after the do-nothing loops are done.

Would appreciate if you could clarify what you said.

thanks,
- Anand
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One of them might do 100000 times. Count the two very carefully and see how many times they run.
 
Anand Hariharan
Rancher
Posts: 280
VI Editor C++ Debian
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Campbell Ritchie:
One of them might do 100000 times. Count the two very carefully and see how many times they run.



Thanks for pointing that out. I missed the second loop starts from 1 and not 0.

Good catch.

- Anand
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So the second loop will doubtless be much quicker, only having to iterate 99999 times.

You need to get attuned to the niceties of the for loop, so you can pick up that sort of thing quickly. Lots of practice required.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

So the second loop will doubtless be much quicker, only having to iterate 99999 times.


Good one, although you should probably use a smiley to indicate the irony; I'm afraid it might be lost on some people.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What irony?

Actually this sort of question comes up every now and again, and sometimes I try it myself, and I get results something like this

Algorithm A Algorithm B
12.56 16.87
11.76 17.80
14.97 16.50
18.32 18.31
11.97 12.87
16.82 18.97

What I notice is that there is considerable variation in the times, and (in some instances) the slower times for algorithm A are slower than the faster times for algorithm B, and there is one instance where algorithm B is actually faster. So I have given up worrying about that sort of performance question.
There are a few instances where it does matter. I was taught that selection sort is faster than bubble sort; both ran in O(n^2) (quadratic time), and I concocted a 1000000-member int[] to try it out on. Selection sort was faster, about 1 hour 39 minutes, and bubble sort took a whole 1 hour 40 minutes. I tried a recursive merge sort (O(n log n)) on a similar array and it was a bit faster. It took slightly more than 0.4seconds.

By the way, Anto, how long did your loops take to run? And what does the body of the Math#max method contain?
 
Ulf Dittmer
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What irony?


Sorry, I thought the "much quicker" was supposed to be an ironic jab at the fact that the "up" loop was one iteration shorter, while in reality most CPU/JVM combinations are able to count down faster than up. (A quick test shows this to be true on my machine, although with a loop that runs 100 times as long. A disassembly with javap shows that different opcodes are being generated for both loops, which probably accounts for the difference.)
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wonder where you found that online test. It's not a very good test; the question is (almost) meaningless, and doesn't really teach you anything useful about Java.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When I tried it, the results vary; here are three runs of something very similar with 1000000 repeats

java trivia.LoopSpeedTest 1000000
Time when idle 2.949�s
Time when ascending 2919.964�s
Time when descending 2302.834�s
Time when idle 2.175�s
[Campbell@queeg applications]$ java trivia.LoopSpeedTest 1000000
Time when idle 2.290�s
Time when descending 36417.470�s
Time when ascending 5343.394�s
Time when idle 1.697�s
[Campbell@queeg applications]$ java trivia.LoopSpeedTest 1000000
Time when idle 2.579�s
Time when ascending 30165.420�s
Time when descending 6139.734�s
Time when idle 1.965�s
[Campbell@queeg applications]$

I randomly set it to go up first or down first to avoid optimisation effects, and here I have two downs faster and one up faster, but the actual times vary between 2.3ms and 36ms. The "idle" time is how long it takes to call the System#nanoTime() method twice and subtract the results. Just goes to show how unpredictable performance can be.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by myself:
What irony?



You sure I wasn't being ironic there?
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Answer to A : Both loops should not have much difference if they are properly benchmarked and given enough time.

Reason: JVM internally kicks in hotspot for optimization. Loop 2 will be better since it has to check only for zero and doesn't need to load the variable all the time for boundary check. However, this is done internally at runtime when hotspot kicks in. This will NOT be visible with just javap.

Answer to B: Both should not have much difference if they are properly benchmarked and given enough time.

Reason: Here is the Math.max(x,y) code
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
And runtime automatically inlines these sort of things to remove deadcode. So ideally you shouldn't find any major boost with A/B

Hope this clarifies.

~Rajesh.B
 
Bartender
Posts: 2856
10
Firefox Browser Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Answer to B: Both should not have much difference if they are properly benchmarked and given enough time.

Reason: Here is the Math.max(x,y) code
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
And runtime automatically inlines these sort of things to remove deadcode. So ideally you shouldn't find any major boost with A/B


If the code isn't inlined then we save a method call on #2.
And is there any dead code here?
 
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Never assume. MEASURE. A good optimizing compiler will collapse a "do-nothing" loop and end up with 0 for execution time, just as it will inline method calls if conditions are ripe. Results will vary depending on optimization settings chosen and whether you have debugging enabled. Results will also vary depending on the instruction set capabilities of the target CPU - both the raw commands produced (op codes) and the internal processor caching and pipelining.

Timing should not be considered as absolutely predictable (30 years ago, yes, now, no). Other processes can steal CPU cycles if you're not careful and you're measuring wall clock intervals. "Bubbles" get into CPU pipelines. Things can fall in and out of cache. RAM can go into refresh cycles, and even the "spread spectrum" BIOS option designed to reduce radio frequency noise emission can blur timings.

Bottom line. You can make a career out of anticipatory optimization, but most of that time will be ill-spent. It's better to do a clean, maintainable, straightforward design with room for change and then if there are performance issues, find out where they are and target them,
 
Ranch Hand
Posts: 5399
1
Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Most of the time I saw that performance is not poor because of these small programming techniques but the real problems were because of poor logic, unnecessary repeated calls to DB, poor joins in SQL, poor configuration of app server etc.

my 2 cents.
 
Tim Holloway
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by R K Singh:
Most of the time I saw that performance is not poor because of these small programming techniques but the real problems were because of poor logic, unnecessary repeated calls to DB, poor joins in SQL, poor configuration of app server etc.

my 2 cents.



Yup. Optimizing-in-the-small rarely effective - a non-optimized heapsort can generally annihilate even the most finely-coded bubble sort, but I used to run into inappropriate use of bubble sorts all the time back in may mainframe days when we had no option but to use assembly language (COBOL didn't work for OS-level code). They'd code bubble sorts anyway, since it's the only sort you could get up and debugged in a day or 2 when using assembler.

In fact, one of the most impressive optimizations I ever encountered required no programming changes at all. We had a system that was bringing down the mainframe every day at 4pm. Crashing a !!! MAINFRAME! As in "re-IPL" (which is mainframe-ese for reboot). Mainframes aren't like Windows machines. A program that blows is supposed to be terminated and processing continues. You re-IPL a mainframe once a week, if that often, and then only at a scheduled time.

A one-line config file change made the whole problem evaporate.
 
Ranch Hand
Posts: 2187
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are many, many different types of Java Virtual Machines. Some may execute specific code faster than others, e.g. Microsoft JVM, J9, HotSpot, JRockit.

As mentioned, this is a poor question.
 
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

my 2 cents.


Your 2 cents are worth at least a dollar! Many of the responses to this thread are music to my ears
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1) For the first code, 1) comparison to zero in a loop is usually faster
2) For the second code, I suspect that 2) will be faster as it doesn't involve any method call.
 
Tim Holloway
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Yves Zoundi:
1) For the first code, 1) comparison to zero in a loop is usually faster
2) For the second code, I suspect that 2) will be faster as it doesn't involve any method call.



Well, it would be, but as I mentioned earlier, most modern compilers work by building up a syntax tree then tweaking the tree several times at both macro and micro levels before actually generating the code. Not like in the 1970's where I could look a the source code and reliably predict what kind of assembly language would come out the other end of the compiler.

You could, of course, disassemble the bytecodes, but the JIT compiler is also prone to extensive rearrangement. So the best best it still to measure. And not to worry about saving milliseconds if there's an algorithm that's gobbling up minutes.
 
reply
    Bookmark Topic Watch Topic
  • New Topic