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()


Revision #3
Created 2023-02-15 20:29:28 UTC by MyroP
Updated 2023-02-16 20:52:41 UTC by MyroP