Wednesday, August 19, 2009

Some Java Tips

I have been working in Java for more than 5 yrs. Here are few general tips which I found very useful for my coding.

This is not a comprehensive list so I’ll keep updating this post in future as well.

  1. Use ArrayList instead of LinkedList. These are significantly faster.
  2. Instead of creating new Integer/Boolean/Float etc. objects, use Integer.valueOf and so on. These methods are 3.5x faster than creating new objects every time. They use JVM caching and other caching tactics to do this. Normally values from 1 to 100 are guaranteed to be in cache.
  3. Use HashMap instead of Hashtable when synchronization is not an issue.
  4. “double” is faster to calculate than “float”.
  5. Use thread pooling instead of creating new threads for every server request (if you expect high volume of requests). Threads are light-weight but they still consume significant resources for creation each time.
  6. Java programs can be compiled into native .exe formats. use MinGW’s gcj tool to do this. As of now, this tool can compile only console applications and not GUI applications like Swing. But it has great support for SWT based applications and its free!
  7. Use StringBuffer rather than the string concatenation operator (+)
  8. Reuse objects where possible
  9. Iterator.hasNext() and Enumerator.hasMoreElements() do not need to be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead
  10. Creating an exception is a costly procedure, because of filling in stack trace
  11. Generic integer parsing may be overkill for converting simple integer formats
  12. Don't optimize as you go. Write your program concentrating on clean, correct, and understandable code
  13. Use profiling to find out where that 80% of execution time is going, so you know where to concentrate your effort
  14. Compile with optimization flag, javac –O
  15. Synchronizing on methods rather than on code blocks is slightly faster
  16. ints are the fastest data type
  17. Null out references when they are no longer used so that garbage collection can reclaim their space
  18. Use maximum caching when possible to enhance performance

Will be posting more.

1 comments:

Anonymous said...

Thanks for the tips

Post a Comment