- Home /
Static reference cost
Hey,
Let's say that i have some singleton classes, like this for example:
public class Player : MonoBehaviour
{
public static Player instance;
void Awake()
{
instance = this;
}
}
Is it fine to use Player.instance a lot in other scripts, or should cache it in a variable on start and use that instead?
Answer by IgorAherne · Nov 11, 2017 at 07:25 AM
calling Player.instance is ultra cheap. It's as negligible as a straw against a huge metal beam
Nice analogy ^^. Fun fact: static references are actually faster than instance fields. static fields can be read from / written to with a single opcode. Instance fields always need the "this" pointer pushed on the stack before they can be read / written.
However do not start using static fields all over the place because they are "faster". This is beyond any recognisable scale. Also keep in $$anonymous$$d the code is finally JIT compiled to native code. So the actual implementation looks different
Your answer
Follow this Question
Related Questions
Using static properties that return _instance.variable... 0 Answers
Remnant Empty Game Objects for Static Scripts 1 Answer
Having a static GameObject pointing to a prefab? 1 Answer
Don't render GameObject on load if already hit by player? 1 Answer
Why should I use a game object for non-physical things? 2 Answers