The JITThe JIT reads ahead through each class and compiles it into native code before it is executed. This results in improved execution time, but slower object creation. With most applications, the JIT speeds things up, but with some, where lots of Objects are being created for example, it can actually slow things down. Some JITs have a lot of options which can alter the tradeoff, but many don't. If you want to turn off the JIT, it can be done with the following option:
Some Miscellaneous Speed DemonsStringsStrings are horrendously slow, take the following example:
At first glance it doesn't look too bad on surface, but in reality it is one of the worst things for slowing things down when you do a lot of String operations, here's what happens. System.arraycopy() is used to copy y and z into a temporary StringBuffer and then toString() is called on the temporary StringBuffer. Try using StringBuffer directly when performing operations such as these. I/OAlways wrap a BufferedReader around an InputStream, and a BufferedWriter around an OutputStream. Reading one byte at a time from a stream is just too slow. GraphicsOveride the repaint() method and use clipping when implementing custom graphics. Use doublebuffering. Static InitializersMake use of them, for those that don't know, they are a block of code contained in curly braces which gets called the first time an object is initialized. They are very handy for all sorts of things, and can be use to do constructor work which only needs to be done once for all instances of a class. ProfilingProfile your classes to determine the bottlenecks. A profiler which comes with java is the -prof option. Run your class using java -prof myclass. Java will dump information about the execution to the local directory. Make use of lessons learned with other languagesA lot of optimizing techniques apply to all languages, use them. For example read through the article: Performance Programming in C++, by Jorris Timmermans, it has a lot of content which can be applied to Java among others. Most important are the use of bit shifts and loop optimization. Being careful about which primitives you useAs a rule of thumb, ints are faster than longs and floats are faster than doubles, use them in preference wherever possible. Make use of threadsThis isn't an optimization thing, but make use of threads when responding to GUI actions, rather than locking the application, the GUI will appear to be much more responsive, than if all the processing was done before the handler returned. Final NoteThese are basically all a collection of ideas I have come across in my year as a Java Programmer so far, I'll probably come across many more in the future. None of the things above are laws, they aren't necessarily the fastest ways. As well as in books which I don't remember the title of ;-) further information can be found on byte codes and the like at: http://www.cs.smu.edu/~jch/java
|