aspose file tools*
The moose likes Performance and the fly likes Java performance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Java performance" Watch "Java performance" New topic
Author

Java performance

Amol Pawar
Greenhorn

Joined: May 02, 2004
Posts: 1
What are tips to improve any java application performance. I could only come up with following.

- Use Stringbuffer instead of String while concatenating string objects.
- Use localized variables as much as possible
- Always close database and file objects in finally before returning from methods
- Using Arraylist instead of Vector and Hashmap instead of Hashtable since Vector and Hshtable are synchronized where ArrayList and HashMap are not.

Thank you
Amol Pawar
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10927
    
  12

you're usually served better by writing clear, readable code tahn by micro-tweaking things to get 'better performance'.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
byronc Ozzie
Greenhorn

Joined: Jul 12, 2010
Posts: 7
Amol Pawar wrote:What are tips to improve any java application performance. I could only come up with following.

- Use Stringbuffer instead of String while concatenating string objects.

To a point its no always quicker - make sure you make constants of your strings so they are not reproduced constantly

- Use localized variables as much as possible

why - they then have to be created and collected all the time

- Always close database and file objects in finally before returning from methods

why? - surely a pool of open connections is faster than opening and closing all the time

- Using Arraylist instead of Vector and Hashmap instead of Hashtable since Vector and Hshtable are synchronized where ArrayList and HashMap are not.

true



Thank you
Amol Pawar


Byron
website design - my immigration to Sydney
byronc Ozzie
Greenhorn

Joined: Jul 12, 2010
Posts: 7
fred rosenberger wrote:you're usually served better by writing clear, readable code tahn by micro-tweaking things to get 'better performance'.


it depends what the purpose of your software is - if your writing low latency high throughput software thats might not be true. why do people always answer like this when its a forum about performance...
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12682
    
    5
Why? Because of many programmer-years of experience, thats why.

Us old-timers have seen so many "tips" and "tricks" promoted that we tend to react that way.

Yes, there are good practices which are easy to implement and do not obscure the clarity of the code.

The number-one best advice is to use the algorithm to match the problem.

If you really have a measured performance problem with low latency high throughput software, you can probably get some valuable suggestions here.

I have always found this site to be useful.

Bill

Java Resources at www.wbrogden.com
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10927
    
  12

byronc Ozzie wrote:why do people always answer like this when its a forum about performance...

if you tweak something that saves you 1 millisecond, and your uses save that 100,000 times a day, you have increased your performance by (roughly) 2 minutes a day, or (again, roughly) 12 hours a year.

If, when you go back and debug that code, it takes you an additional 2 days to figure out what the hell you were thinking (and believe me, 2 days to figure out and fix some esoteric bug is being generous), you have now spent more time fixing it than you saved in the first place.

Whereas if you write clear, easy to read and understand code, your users will probably never notice that millisecond of time they lose, and you won't spend 2 days figuring out the bug.
Jon Hxx
Greenhorn

Joined: Mar 08, 2011
Posts: 3
The String implementation has been changed in JDK 1.3 or JDK 1.4 which some of the previous performance penalty has been gone. The issue I had with your list is that those are interesting but not necessary the most important or most common problem in performance. Here are some of the list that I suggest you to look into
Top J2EE application performance problems
Prashant Saraf
Ranch Hand

Joined: Sep 25, 2006
Posts: 52

You can check some of automation in code review by adding Findbug/PMD/checkstyle they find excelet performance realted issue. Initially you need to configure them according to your requirments.

Thanks
Prashant Saraf
joy b chakravarty
Ranch Hand

Joined: May 16, 2011
Posts: 62

Amol Pawar wrote:
- Use Stringbuffer instead of String while concatenating string objects.


Use StringBuilder instead it avoids the overhead of synchronization i.e of-course if you don't need it.




Cheers, Joy [SCJP 1.4, SCBCD 5.0]
get high on alcohol, algorithm or both
Ravi Majety
Ranch Hand

Joined: Feb 26, 2009
Posts: 59

- Always close database and file objects in finally before returning from methods

why? - surely a pool of open connections is faster than opening and closing all the time


Here some modification is required as follows

Always Close connections and file objects in finally before return methods.

Because , a connection is available again in pool of connections when it was freed by the programming(ie., by closing the connection )


Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4639
    
    5

Premature optimization is the root of all evil.

Donald Knuth
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10927
    
  12

Any tip that says "Always do X, Y, or Z" is wrong.
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Are you saying we should always ignore them then?


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10927
    
  12

only some of the time...including my own.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 396

Is StringBuilder a such a saver over StringBuffer as Java moves forward ie

modern JVM optimisations make great in roads into removing unnecessary synchronisation e.g. lock coarsening in theory your JVM can optimise away the problem.

http://www.ibm.com/developerworks/java/library/j-jtp10185/index.html

The story goes if there are any obvious speed ups like this some one is working on a JVM optimisation for it and you'd be better just writing the code and preforming your profiling after or you run the risk of confusing the JVM.


Maybe you should just run the latest JVM ;-)


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4639
    
    5

Chris Hurst wrote:Is StringBuilder a such a saver over StringBuffer as Java moves forward

As a general rule, over time, things that do the same thing are optimized so they take the same amount of time/resources/memory.

In the specific case, StringBuilder is advertised as not being thread safe, and StringBuffer is thread safe. This is a fundamental difference. On lightly loaded systems with no thread contention, it may be a small difference. On a system/application with lots of lock contention, this can be a huge difference.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 396

In the specific case, StringBuilder is advertised as not being thread safe, and StringBuffer is thread safe. This is a fundamental difference. On lightly loaded systems with no thread contention, it may be a small difference. On a system/application with lots of lock contention, this can be a huge difference.


I wasn't saying actual lock contention was cheaper (though actually it does in theory in some scenarios ;-) e.g. adaptive locking) but presumably if you have lock contention you need some form of synchronization somewhere anyway.

I agree lock contention effects performance but what I'm saying is just using StringBuilder is no longer just better than StringBuffer in theory, you now have to look at the context more ie can the JVM optimise out synchronization in a given scenario if it can't then possibly you needed a lock anyway ;-) previously also you could improve on StringBuffer by using StringBuilder with a coarser lock however this also potentially comes for free now. A whole load of potential lock acquistion and release can jump out the window, if the new JVM can prove it was never necessary.

I think most people by instinct would use StringBuilder (good idea( but with later JVM's it is a much less of an obvious win than it was in theory. Also I've found a lot of code that tries to avoid the evils of deadlock and lock contention just shoots itself in the foot with visibility , happens before ordering issues i.e. they never really understood what synchronization fully does and just thought it was about locking :-(
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4639
    
    5

Chris Hurst wrote: if you have lock contention you need some form of synchronization somewhere anyway.


Which gets the the heart of the design question. Often, you don't have any possibility of a need for synchronization, so having the software even acquire the lock is wasted effort. StringBuilder don't think about locks. If you *know* that you don't need them, then using StringBuffer has overhead you don't need.

Whether this is a real issue or just premature optimization is a separate topic.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 396

so having the software even acquire the lock is wasted effort.


I think my point it is theory it doesn't even acquire the lock i.e. no difference ...

I've stated in the past that trying to avoid synchronization is generally a bad idea. The arrival of optimizations such as lock elision adds yet one more reason to avoid trying to eliminate synchronization -- the compiler can do it automatically where it is safe, and leave it in place otherwise.
- Brian Goetz

Brian's example ...



Because no reference to the Vector ever escapes the getStoogeNames() method, it is necessarily thread-local and therefore any synchronized block that uses it as a lock will have no effect under the JMM. The compiler can inline the calls to the add() and toString() methods, and then it will recognize that it is acquiring and releasing a lock on a thread-local object and can optimize away all four lock-unlock operations.

I've stated in the past that trying to avoid synchronization is generally a bad idea. The arrival of optimizations such as lock elision adds yet one more reason to avoid trying to eliminate synchronization -- the compiler can do it automatically where it is safe, and leave it in place otherwise.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4639
    
    5

Chris Hurst wrote:I think my point it is theory it doesn't even acquire the lock i.e. no difference ...


There is no point in speculating, the code is open source. You can look at it and see it acquire a lock. That is a waste of resources.

Now, if you want to argue that its not much of a waste, we can start over beers. But there is no theory in question here. Simple fact that StringBuffer is synchronized.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2970
    
    9
Or alternately, it may be a waste of resources for the JIT to perform the extra escape analysis required to determine that a given lock never has any actual significance (being accessible to only one thread) and can thus be safely removed. I think that's what Chris is alluding to. But as far as I know escape analysis was still experimental as of JDK 6, and is off by default. But it will probably become more reliable and powerful over time.

Personally I would prefer that classes like StringBuffer and Vector just be deprecated entirely. Calling them "thread safe" is an unfortunate mistake by Sun, since it's rare you can do anything useful with them in a multithreaded environment without requiring additional synchronization. Trying to sync from within those classes is just a bad idea, as you often need synchronization that spans two or more method calls. Oh well...
rinku jain
Greenhorn

Joined: Jan 04, 2011
Posts: 26
use bitwise operator where ever possible

optimize the loops

Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

...or alternatively don't bother unless you prove you have a performance problem and these small changes would fix it (I recommend re-reading Fred's response).
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 396

...or alternatively don't bother unless you prove you have a performance problem and these small changes would fix it (I've recommend re-reading Fred's response).


100 % agree .. though its still a fun mental exercise to look at possible enhancements .. I always think of it like this if I inherited code to support I'd leave it alone unless I could prove a performance benefit, writing it from scratch I would consider such optimisations as long as they felt natural.
I think most real enhancements are at a data structure, framework, algorithm level.

Anyway just for fun ..

initial data structure size e.g. StringBuilder rather than the default set an initial size if you have a better guess than java i.e. you sometimes see code where you know what the resultant size will be so why not share that info with java ;-) Also getting your hashmap sizes in particular right is obviously another possible winner.
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
A lot of small optimizations can make for a measurable total improvement. Although I agree that you shouldn't "optimize" blindly, clear code is always preferable.

My personal addition to the "things to optimize" list: don't use regular expressions, unless you have to. Using String.indexOf() for finding, or StringBuilder.replace() for replacing is almost always faster than using a variant with regular expressions.

Of course, this again comes down to "use the right algorithm for the right situation".
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Perhaps, though not in my experience (your may be different I'll concede). The key word here is "measurable". If you are not intending to profile and performance test the differences don't bother making the change. Just make your code understandable.
 
Don't get me started about those stupid light bulbs.
 
subject: Java performance
 
Similar Threads
int[] find : converting Vector to int[]
Vector and hashtable inTiger
Ur Program
struts 2 s:radio tag
core java