使用Pimpl的高级变体时可能会影响性能

Possible performance hit when using an advanced variation of Pimpl?

本文关键字:影响 性能 Pimpl 高级变 使用      更新时间:2023-10-16

想象一下。

我希望创建不公开任何底层实现的类。即使这样也不意味着有一个指向实现的指针。

我会使用全局对象池来完成此操作。

像这样的东西。

在类TestImpl中实现的类Test。

构造Test时,它会在全局对象池中为自己创建一个TestImpl。

对象池基本上是每种类型的映射。键将是测试实例的内存地址,值将是相应的TestImpl。所以每次调用Test上的成员函数时,它首先从对象池中获取相应的TestImpl,使用this指针作为键。

这种对象池当然必须同步,需要锁。

你认为这样的解决方案会带来多大的性能冲击?

ifc.h

struct ifc {
    virtual ~ifc() {}
    virtual void api() = 0;
    static ifc* create();
};

impl.cc

#include "ifc.h"
struct impl: ifc {
    virtual void api() override;
}
void impl::api() {
    // code here
}
ifc* ifc::create() {
    // or use shared pointer / untrusive pointer and return object back to a pool
    // if dynamic memory allocation is not desired (but rather just keep it simple  
    // and plug something like TCMalloc first (which does low level pooling)
    // and see if it gets better)
    return new impl();
}