I'm creating a game with a lot of elements. Should I store all components that I'll eventually access on class variables (memory) or should I access them when running the script(processor)?

Example:

private SpriteRenderer sprite;

void Start () {
   sprite = GetComponent<SpriteRenderer>();
}

public void StartMovement()
{
    sprite.doSomething();
}

VS

void Start () {

}

public void StartMovement()
{
    GetComponent<SpriteRenderer>().doSomething();
}
up vote 4 down vote accepted

Yes you should store them. Storing a reference takes up only 4 or 8 bytes (32bit vs 64bit) space in memory while fetching them using GetComponent() can use a lot more, while also it will be a lot slower to execute.

Premature optimization (which you seem to be doing) is a bad thing. You should worry about memory consumption and performance, but not before it becomes a problem. If something is known to be slow (like using GetComponent() inside the Update() function), you should design your code around that fact. Make the game first, and only after you profile it if it uses too much memory you should start optimizing.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.