Object-oriented – Trying to get a better understanding of object-oriented design’s performance pitfalls

chigh performanceobject-oriented

I'm currently in a high-performance computing class taught in C++. Usually, I do work in C#, meaning everything is taken care of for me, and optimization comes behind maintainability and higher-level features. It's like… a nice productivity furnace that keeps me nice and warm in the programming project winter at the expense of my CPU cycle/cache miss electricity bill. However, now that I'm in C++ and efficient algorithm land, that stuff takes a back seat to optimization.

Since most of my work has been in C#, object-oriented programming is sort of my style. However, I have been reading/hearing more and more about how object-oriented code is an enemy of performance. As my understanding of software architecture shifts from being exclusively about class structure and encapsulation to understanding how things are disposed of from L1 cache and pipelining, I'm trying to understand the real reasons why object-oriented design (especially as it applies to C++) causes waste of hardware resources. Can you guys give me a few basic reasons why it impacts computer performance? I know there are other debates about OOP, but I'd like to just keep it to performance on a hardware and algorithmic level.

Best Answer

Many of the OOP's performance problems come from indirection caused by inheritance and virtual methods. The virtual methods are problematic because:

  • They take more time because of virtual table lookup
  • Cannot be properly optimized, eg. using inlining for example. Or at least it is too hard to do it.
  • In some languages, they are forced to be reference types, so when you have many of them, they are scattered in memory instead of continuous block, hurting cache.

If you remove this, you will loose major point of using OOP, like modularity or extensibility, but you will gain a performance. The major advantage of C++ (especially compared to Java and C#) is you can pick where you want this indirection and where you want non-OOP way of doing things. You could do this in C#, but it is not that nice and easy as in C++.

Related Topic