单例模式性能问题 [英] Singleton Pattern performance issue

查看:72
本文介绍了单例模式性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查一个使用很多单例类和访问权限的现有代码.我正在尝试提高此代码的性能.

I am reviewing an existing piece of code which uses a LOT of singleton classes and accesses. I am trying to improve the performance of this code.

想到的一件事是优化Singleton :: getInstance()代码段.

One thing that comes to mind is to optimize the Singleton::getInstance() piece of code.

我倾向于不使用Singleton :: getInstance(),而是用两个调用将其替换为结构.

Rather than using Singleton::getInstance(), I am inclined to replace this with structure with two calls.

a.一个可以创建和准备单例实例的函数,例如Singleton :: prepareInstance(),它将在子系统开始时被调用一次.b.getInstance()的内联实现,它将仅返回引用而不检查其是否有效.

a. A function that would create and prepare the singleton instance, like Singleton::prepareInstance() that would be called once at the start of the subsystem. b. an inline implementation of getInstance() that would just return the reference without checking if it's valid or not.

这是可行的解决方案吗?有什么办法可以改善吗?

Is that a viable solution? Any way to improve on this?

我当前的Singleton :: getInstance()代码看起来像这样

The current Singleton::getInstance() code that I have looks like this

Singleton * Singleton::getInstance() {
    if(m_instance == NULL) {
        m_instance = new Singleton();
    }
    return m_instance;
}

πάνταῥεῖ提到的方法更快吗?

Is the approach mentioned by πάντα ῥεῖ any faster?

推荐答案

b.getInstance()的内联实现,该实现仅返回引用而不检查其是否有效.

b. an inline implementation of getInstance() that would just return the reference without checking if it's valid or not.

为什么需要检查有效性?我的单例 GetInstance()实现通常如下所示:

Why there's need to check for validity? My singleton GetInstance() implementations usually look like this:

Singleton& Singleton::instance() {
    static Singleton theInstance;
    return theInstance;
}

我怀疑这样的代码是否会对性能产生影响,也不必检查任何内容的有效性.

I doubt such code should have any performance impact, neither it's necessary to check anything for validity.

这篇关于单例模式性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆