Speed-up your java code


Few tips that will speed-up your java code

Finalizers: object that overwrites the finalize() method (“Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.”) is slower!(for both allocation and collection) if it’s not a must, do clean ups in other ways ( e.g. in JDBC close the connection using the try-catch-finally block instead)

New is expensive: creating new heavy object() on the heap is expensive!, it’s recommended to recycle old objects (by changing their fields) or use the flyweight design pattern.

Strings : (1) Strings are immutable which mean that upon usage of the + operator between 2 strings the JVM will generate a new String(s1+s2) on the heap (expensive as I just mentioned), in order to avoid that, it’s recommended to use the StringBuffer.(Update) since JDK 1.5 was introduced  StringBuilder is a better option than Stringbuffer in a single-threaded environment.

(2) Don’t convert your strings to lower case in order to compare them, use String.equalIgnoreCase() instead.

(3) String.startswith() is more expensive than String.charat(0) for the first character.

Inline method: inline is a compiler feature, when you call a method from anywhere in your code, the compiler copies the content of the inline method and replace the line that calls the method with it.

Obviously,It saves runtime time: (1) there is no need to call a method (2) no dynamic dispatch.

In some languages you can annotate a method to be inline, yet in Java it’s impossible, it’s the compiler decision.

the compiler will consider inline a method if the method is private.

My recommendation is to search in your code for methods that are heavily used(mostly in loops) and annotate those method as private if possible.

Don’t invent the wheel: the java api is smart and sophisticated and in some cases use native implementation, code that you probably can’t compete with. unless you know what you are doing (performance wise) don’t rewrite methods that already exists in the java API. e.g. benchmarks showed that coping and array using a for loop is at least n/4 times slower than using System.arraycopy()

Reflection: reflection became much faster for those of you who use the most recent JVMs, yet using reflection is most certainly slower than not using it. which mean that you better avoid reflection if there is no need.

Synchronization: Some data structures auto-support concurrency, in case of a single thread application don’t use those to avoid overhead e.g. use ArrayList instead of a Vector

Multithreads: in case of a multi processor use threads, it will defiantly speed up your code, if you are not a thread expert some compilers know how to restructure your code to thread automatically for you. you can always read a java threads tutorial as well

Get familiar with the standard data structures:   e.g. if you need a dast for puting and retriving objects use HashMap and not an ArrayList. (O(1))

Add an id field, for faster equals(): object that contains many fields are hard to compare ( equals() wise), to avoid that add an id(unique) field to your object and overwrite the equals() method to compare ids only.

Be careful, In case  your code already works, optimizing it is a sure way to create new bugs and make your code less maintainable!

it’s highly recommended to time your method before and after an optimization.

Advertisements

17 thoughts on “Speed-up your java code

  1. Actually, just always use StringBuilder instead of StringBuffer.
    When was the last time you needed to append a string from several threads? Never, no-one ever has.

    About, don’t re-invent the wheel, absolutely correct. If I had a dollar for every time I stumbled across a re-implementation of stuff in the java.utils package, I’d make Bill Gates look poor.

    Regarding threads, learn, know and use the new java.util.concurrent package.

    Good job with the post.

    -Paul

  2. very smart and good advices,
    unfortunately, it doesnt change much on the field.
    The main performance killers I acquaintance with are when using too much RMI,
    And when using uncarefull and unsmartly,O/R mapping like EJB , or hibernate.
    They just allways do this nasty thing of full row data fetch, and full update,
    when you just need to update this little fractionally field of apartment number for example.

  3. > New is expensive: creating new object() on the heap is expensive!,
    > it’s recommended to recycle old objects (by changing their fields)
    > or use the flyweight design pattern.

    I do not believe that this is the case any longer. A good read is Java theory and practice: Garbage collection and performance (http://www.ibm.com/developerworks/library/j-jtp01274.html), which comments:

    In his “Performance Myths Exposed” talk at JavaOne 2003, Dr. Cliff Click offered concrete benchmarking data showing that object pooling is a performance loss for all but the most heavyweight objects on modern JVMs.

    > Synchronized method and code block will make your
    > code ~5-2.5 times slower, avoid annotate your
    > method and code block if it’s not necessary.

    Uncontested synchronization certainly is not going to have that much of an impact. If you truly do have multiple threads contesting for a resource, then you may see a significant impact, but it may well be worth it. Take a look at the read/write locks in java.util.concurrent.locks for some good ways to minimize the impact.

  4. -Tip #1 should be: Use a profiler to find the slow spots!

    Otherwise you’re most likely wasting effort and making hard to manage code at the same time.

  5. Pingback: How not to speed-up your java code « Simple Notions

  6. Pingback: Dez listas de dez coisas | Blog Tecnologia e Educação

  7. Pingback: Dicas – 10 listas de 10 coisas « Templário da Tecnologia

  8. Pingback: Thunder-Boy » Blog Archive » 10 listas de 10 coisas…

  9. Pingback: How to improve Java performance / increase Java speed

  10. I have 1 question please answer -I am doing java code as 6 currency pair from 1 min to 8 hours for live chart with 1000 multiplication factor so its taking lot of time to retrieve data from database and to plot the graph so tell me some commands or suggestion what i do to make speed in my java code.
    please its urgent…

  11. Pingback: Java performance steigern / Rechenleistung erhöhen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s