- Home /
Is calling GetComponent multiple times bad?
Is calling GetComponent multiple times bad? Or should I cache it?
For example, let's say I need to access multiple variables of the same component
gameObject.GetComponent<ScriptA>().var1 = 534;
gameObject.GetComponent<ScriptA>().var2 = 3534;
gameObject.GetComponent<ScriptA>().var3 = 456;
gameObject.GetComponent<ScriptA>().var4 = 65;
gameObject.GetComponent<ScriptA>().var5 = 874;
Or should I cache it
ScriptA scriptA = gameObject.GetComponent<ScriptA>();
scriptA.var1 = 534;
scriptA.var2 = 3534;
scriptA.var3 = 456;
scriptA.var4 = 65;
scriptA.var5 = 874;
Is there any performance difference between the two? Dose one generate more garbage than the other?
Answer by Prastiwar · Jan 28, 2018 at 07:37 AM
Yes, you should cache it, GetComponent is expensive, that's all. Practically you want caching everything.
Answer by pako · Jan 28, 2018 at 11:52 AM
As far as I know, there should be no garbage created when you call GetComponent
, because you'd just be calling a method of the GameObject
class, not creating and destroying an object, which is what would create garbage.
However, performance would be affected, because whenever you call a method, you create overhead, and that's what you want to avoid.
Therefore, when you call gameObject.GetComponent<ScriptA>()
five times, instead of once and caching it, you'd be creating 5 times the overhead. Although this may, or may not be noticeable degradation in the performance of the game, it would be good practice to avoid these extra calls, especially when they would be made frequently, e.g. inside Update()
.
Your answer
Follow this Question
Related Questions
Huge Lag Spikes on using (WebClient webClient) 1 Answer
Multiple Cars not working 1 Answer
Performance issue due to too many if statements. 2 Answers
Reference Variables and Drag-And-Drop 0 Answers