Monday, November 25, 2013

improve java code performance

I got a interview question “How to improve java performance”.

It is a very big question, not easy to cover all of them.

  • use the correct java class, e.g.
    • StringBuilder instead of String + String
    • ArrayList for quick iteration, LinkedList for quick insert and delete
  • Avoid unnecessary Loop
    • e.g. loop a list to get avg and sum, do them in the same loop.
  • REST instead of Web service
  • JSON instead of XML
  • read/write large file
    • Minimize I/O operations by reading an array at a time, not a byte at a time. An 8Kbyte array is a good size.
    • Minimize data copying between the JVM/OS, internal buffers, and application arrays. Use FileChannel with memory mapping, or a direct or wrapped array ByteBuffer.

  • don’t use synchronized if thread safe is not need

    • Minimize thread synchronization locks if you don't need thread safety. Make fewer method calls to a thread-safe class

  • Run program in parallel, thread pool

    • e.g. I used to work on a batch job. In our database, we have address without latitude and longitude. To get the  latitude and longitude, we need send the address to a web service and it would return the lat/long. We have about 3000 address need updating. To do it one by one, it took about an hour. I used thread pool, maximum 10 threads and the job was finished in 15 minutes.

  • reuse high cost resources

    • like data base connection

  • database side

    • use cash

    • avoid N+1 query

    • don’t join unnecessary tables

No comments:

Post a Comment