GetComponent<>()
Many of you may already know that calling GetComponent
is pretty expensive in Unity.
But how expensive is it in Udon? Let's see!
I executed two methods Benchmark1
and Benchmark2
and compared their execution time.
public override void Benchmark1()
{
Labyrinth labyrinth = GetComponent<Labyrinth>();
for (int i = 0; i < 1000; i++)
{
labyrinth.InitGrid(2, 2);
}
}
public override void Benchmark2()
{
for (int i = 0; i < 1000; i++)
{
Labyrinth labyrinth = GetComponent<Labyrinth>();
labyrinth.InitGrid(2, 2);
}
}
Both methods do the same thing, except that Benchmark2
calls GetComponent
inside a for-loop
B1 : 60.0576 msĀ
B2 : 111.367 ms (1.85 times slower)
The difference is very noticeable, I'ld hightly recommend to call GetComponent<>() only once, for instance in Start()
No Comments