Sunday, February 28, 2010

The performance impact of object orientation

Today's new Javamex article looks at the performance impact of using an object-oriented approach vs an optimised, non-object-oriented approach in a case where the OO approach requires high object throughput. Specifically, we look at the case of calculations with complex numbers.

The basic tenet is that the most intuitive program design is to have a complex number encapsulated as a Java object, and furthermore, as an immutable object. This means that at each individual step in a calculation, a brand new object is created. However, performance measurements suggest that using immutable objects is only around 28% slower than using mutable objects, whilst the codability and maintainability impact (threading issues; bugs introduced by forgetting to copy objects and hence making accidental modifications to an obejct) may be considerable.

In our example, a version of the algorithm that does away with encapsulation and "inlines" its calculations on raw double primitives is more than twice as fast, as perhaps might be expected. On the other hand, "only" being between twice and three times as fast means that a comparable improvement will be possible in some applications by making use of more processors, or potentially making other algorithm improvements, whilst the codability and maintainability implications of not using encapsulation become more severe for more complex applications.