Java discussion forum
The cost of Java object orientation in mathematical calculations: performance of optimisations
Now it's crunch time. We presented an example of "truly" object-oriented complex number calculation, using an immutable ComplexNumber class. Then on the previous page we presented two optimisations aimed at reducing object creation, in the extreme case eliminating it altogether. What performance improvements do these approaches bring?
The figures below give example timings in milliseconds for creating a 1280x1024 fractal using: (a) the optimised version that does away with ComplexNumber altogether; (b) the semi-optimised version that uses a mutable version of ComplexNumber; (c) the original version using a mutable version of ComplexNumber:
1. Mean of ten runs, after three "dummy" runs to warm up the JVM, on an AMD Athlon TK-55 (1.8 GHz), JDK 1.6 update 18.
From these results, it appears that the main architectural decision is whether to use object encapsulation or not, and not so much about the implementation of encapsulation (mutability vs immutability).
Avoiding encapsulation altogether brings a tangible speed increase, as we might expect. On the other hand, for some applications, using additional processors may be a viable and more maintainable way of achieving a 2x or 3x speed increase. And the codability issues associated with doing away with encapsulation may be significant in many cases.
Should you make instances of the encapsulating class immutable? This essentially hinges on whether gaining an approximate 30% speed increase is worth the maintainability risks that you're trading it for. If you are working in a multi-threaded application where thread-safety of the ComplexNumber class is important, then adding more processors may well be a more viable way of achieving this speed increase, and the risk of introducing bugs by removing this built-in thread-safety and requiring the programmer to manually make copies of objects in the right places is probably not worthwhile. In a single-threaded environment where additional processors are not an option, other types of optimisation— such as looking for ways to reduce the mathematical expressions involved in the application— are likely to be worth exploring before introducing the other maintainability issues mentioned.
Copyright © Javamex UK 2010. All rights reserved.