Java performance tips

前端 未结 14 1870
傲寒
傲寒 2021-02-01 20:04

I have a program I ported from C to Java. Both apps use quicksort to order some partitioned data (genomic coordinates).

The Java version runs fast, but I\'d like to get

14条回答
  •  没有蜡笔的小新
    2021-02-01 20:48

    Obviously, profile profile profile. For Eclipse there's TPTP. Here's an article on the TPTP plugin for Eclipse. Netbeans has its own profiler. jvisualvm is nice as a standalone tool. (The entire dev.java.net server seems to be down at the moment, but it is very much an active project.)

    The first thing to do is use the library sorting routine, Collections.sort; this will require your data objects to be Comparable. This might be fast enough and will definitely provide a good baseline.

    General tips:

    • Avoid locks you don't need (your JVM may have already optimized these away)
    • Use StringBuilder (not StringBuffer because of that lock thing I just mentioned) instead of concatenating String objects
    • Make anything you can final; if possible, make your classes completely immutable
    • If you aren't changing the value of a variable in a loop, try hoisting it out and see if it makes a difference (the JVM may have already done this for you)
    • Try to work on an ArrayList (or even an array) so the memory you're accessing is contiguous instead of potentially fragmented the way it might be with a LinkedList
    • Quicksort can be parallelized; consider doing that (see quicksort parallelization)
    • Reduce the visibility and live time of your data as much as possible (but don't contort your algorithm to do it unless profiling shows it is a big win)

提交回复
热议问题