May 21, 2013

PIMPL Pattern - Me No Likey

I haven't used the PIMPL pattern so far. I remember reading about it once long time ago, but was just not convinced it's something I want.

And now I'm working in a codebase where PIMPL patters are abundant. My verdict? Yeah I don't like it. I just don't see the benefit of it in game programming. So what are the benefits of the PIMPL pattern? I can only guess these two:

  1. clear separation between API design and implementation: for example, the grand master designer designs API and minion programmers implement those in hidden places
  2. less header file interdependency = faster compilation time
I don't think #1 means a lot for game programming. Just like in any entertainment business, our requirements keep changing, so are a lot of APIs. Also hiding implementation from other programmers sounds just weird in this industry. We usually have the full access to any source code. After all, we are not library vendors.

I think the main reason why game developers are using the PIMPL pattern is because of #2. C++ sucks with compilation time blaa blaa... But there are other way to make the build faster and PIMPL is definitely not the fastest one I have seen. Then is it incredibuild, which is pretty expensive? No the fastest one(I have seen) is Unity builds, which is completely free.(duh)

So I don't see benefits of PIMPL at all. Instead, I see more disadvantages:
  1. Code is harder to read: who likes to jump around different classes to see actual implementations? Maybe you do, but I don't.
  2. Discrete memory allocation: you need an extra memory allocation to instantiate the pimpl object. I'd much prefer to have all my members in a class, so that there's only one memory allocation and it's straight-forward to find out the size of an object.
  3. Another pointer dereferencoing = slower: sure. some people might say "it's not that slow." but I'm just nazi about it. one additional pointer dereferencing is probably about 4 cycles extra... but with the separate memory allocation for the pimpl object, there's more chance it would trash cache lines. You can probably avoid it by carefully controlling the allocation order, but it sounds like very tedious work that I don't want to deal with.
So, me no likey.... or am I missing something here?


  1. You can avoid extra memory allocation by keeping an opaque char array in your class. I quite like this idiom, because it forces nice interface/implementation separation.

    1. I personally think having char array and change it as my impl object's size grows or shrinks is more error-prone. It's probably just a personal preference that I don't see huge benefits from separation between interface/implementation that the pimpl pattern offers. But I can also see other people enjoy that kind of separation.