Note that there are some explanatory texts on larger screens.

plurals
  1. POPreventing Singleton Cache Miss in C++
    text
    copied!<p>Is there a way to prevent a cache miss when using singleton objects? Here's my current singleton implementation:</p> <p>SingletonObject.h</p> <pre><code>#pragma once class SingletonObject { public: static SingletonObject* SingletonObject(); static void SingletonObject(); private: static SingletonObject* sSingletonObject; SingletonObject(); ~SingletonObject(); }; </code></pre> <p>SingletonObject.cpp</p> <pre><code>#include "SingletonObject.h" SingletonObject* SingletonObject::sSingletonObject = NULL; SingletonObject:: SingletonObject() { } SingletonObject::~ SingletonObject() { } SingletonObject* SingletonObject::GetSingleton() { if (sSingletonObject == NULL) // cache miss { sSingletonObject = new SingletonObject(); } return sSingletonObject; } void SingletonObject::DestroySingleton() { delete sSingletonObject; sSingletonObject = NULL; } </code></pre> <p>Is there a better way to do this that prevents a cache miss? Is this just another reason to not use singletons?</p> <hr /> <p><strong>Update:</strong> Turns out it really was nothing to do with cache as much as the code generated for stack unwinding and the conditional check in the GetSingleton() call. By explicitly creating and destroying the singleton (instead of demand-creating it), and creating an accessor for the static instance, I was able to avoid much of the overhead and noted a significant speedup in profiling.</p> <p>SingletonObject.h</p> <pre><code>#pragma once class SingletonObject { public: static void CreateSingleton(); static void DestroySingleton(); static inline SingletonObject* GetSingleton() { return sInstance; } private: static SingletonObject* sInstance; SingletonObject(); } </code></pre> <p>SingletonObject.cpp</p> <pre><code>#include "SingletonObject.h" void SingletonObject::CreateSingleton() { if (sInstance == NULL) sInstance = new SingletonObject();` } void SingletonObject::DestroySingleton() { delete(sInstance); sInstance = NULL; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload