0
\$\begingroup\$

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();
}
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .