Basic Java Optimisation Hints

8. Go native ... but only if you have a really good reason

When all else fails you may want to use the Java Native Interface (JNI) to jump out to native, compiled code

You might want to do some really low level, grimey optimisation work without having to worry about garbage collectors, strong type checking and the other elegant abstractions Java offers

You should only look to native code if you know exactly what you're doing and why. Think cost-benefit analysis.

Moving data in and out of the JVM's garbage collected memory space is not free. Calling Java code from native code is slow, and you still have to worry about thread safety

Native code brings with it major development headaches: you loose portability

You're much better to concentrate on algorithmic improvements

When all else fails you can use the Java Native Interface (JNI) to jump out to native, compiled code. "Hang on a minute" you might say, "isn't this tantamount to admitting that Java is slow after all?". Err ... well no it isn't quite, but it is an admission that you might want to do some really low level, grimey optimisation work without having to worry about garbage collectors, strong type checking and the other elegant abstractions Java offers. This is especially true if you're one of those sick-o types who hand code tight SIMD assembly routines to crunch through the inner-most loop of an image processing function or a scientific computation. Don't believe the hype about what modern compilers can do - nothing beats hand-crafted assembler!

This is, of course, you're absolute last resort. Lets be really clear on this point: you should only look to native code if you know exactly what you're doing and why. Think cost-benefit analysis. Profile your application extensively, understand precisely how much time each routine uses and account for every precious CPU cycle. Then way up any performance boost against the costs associated with going native. Moving data in and out of the JVM's garbage collected memory space is not free. Calling Java code from native code is slow, and you still have to worry about thread safety. Once all this is wayed up you may not see a speed gain with native code. Worse still native code brings with it major development headaches: you loose portability; you have to deal with the seedy underbelly of the JVM; debugging becomes a nightmare. In my experience you're much better to concentrate on algorithmic improvements since native code will only buy you a percentage or two in the margins.

In fact the reason I've included this tip in the article is to try and convince you not to go native. Some gung-ho types dive into native code at the first hint of performance trouble. But a "rush of blood to the head" is not part of many good design methodologies. Less of a recipe for success, most of the time it's either blind enthusiasm or blind panic! My advice is go talk to someone else before ordering that copy of "x86 for Dummies".