我正在审查使用许多单例类和访问的现有代码。我正在尝试提高此代码的性能。
我想到的一件事是优化Singleton :: getInstance()代码段。
与其使用Singleton :: getInstance(),不如将其替换为带有两个调用的结构。
一个。一个可以创建和准备单例实例的函数,例如Singleton :: prepareInstance(),它将在子系统启动时被调用一次。b。getInstance()的内联实现,该实现仅返回引用而不检查其是否有效。
这是可行的解决方案吗?有什么办法可以改善吗?
我当前的Singleton :: getInstance()代码如下所示
Singleton * Singleton::getInstance() {
if(m_instance == NULL) {
m_instance = new Singleton();
}
return m_instance;
}
πάνταῥεῖ提到的方法会更快吗?
b。getInstance()的内联实现,该实现仅返回引用而不检查其是否有效。
为什么需要检查有效性?我的单例GetInstance()
实现通常如下所示:
Singleton& Singleton::instance() {
static Singleton theInstance;
return theInstance;
}
我怀疑这样的代码是否会对性能产生影响,也没有必要检查任何内容的有效性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句