Friday, June 27, 2014

Object-Oriented Programming: the Good, the Bad and the Ugly

Let me clarify. I love OOP. I developed a lot of functionality using OOP and found it is very productive and highly extensible approach. So what's the point?

The Good

What is primary goal of OOP? What are the benefits? Why is it so popular? Where is a magic?

These are simple questions. And I would like to have simple answers. I guess you too. I have this one: it allows to significantly improve the code reuse. How? Because you may use abstractions instead of concrete classes and this fact allows to reuse the functionality based on those abstractions. Why does it matter? Because code reuse is the most effective way to speed up your development.

The Bad

So what's wrong with OOP? Is it the holy grail and silver bullet together? Unfortunately the answer is: no. On the one hand we have development speed up. On the other hand we have the price to use abstractions. Let's discuss it in detail.

Usually the invocation of virtual function is an indirect call. Indirection means that branch prediction mechanism will fail on performing the operation. That causes performance degradation on each virtual call.

Another aspect is the data locality. Recent processor logic is so fast that the actual bottleneck is the physical memory. That's a reason of having several levels of caches on modern architectures. Caches really like sequential operations and hates jumping across the memory back and forth. But any abstraction has the underlying pointer to the associated data, data itself contains pointer to virtual table. So we have several indirections to perform our actions. It would be better to have plain structure in continuous region of memory. Abstractions break up the memory for each object.

Is it important? In approximately 99.99% cases it's not. But when it's important you should take care of that. Fortunately profile-guided optimizations allow you to slightly improve the situation, at least for replacing virtual calls on ordinary function calls in some cases.

The Ugly

I would like to emphasize the last moment of OOP development. There are developers trying to apply their knowledge right after reading the book of GoF, Gang of Four. Don't allow them to commit the code! It's probably the most horrible and ugliest things that I've ever seen.

Conclusion

My conclusion is simple. Apply abstractions only when it's necessary. When performance is important you should try to build your software with minimal usage of abstractions. Because of OOP is like a performance trade off: development speed vs runtime speed.

No comments :

Post a Comment