Skip to main content

Builtin functions vs calculating something manually

Let's say you want to calculate the distance between two vectors.

Some of you would probably write something like this :

distance = Vector3.Distance(a,b);

Others might write something like this (which is how Unity implemented the Distance method) :

float num = a.x - b.x;
float num2 = a.y - b.y;
float num3 = a.z - b.z;
distance = (float)System.Math.Sqrt(num * num 
	+ num2 * num2 
	+ num3 * num3);

In regular C#, that wouldn't make a difference, because C# code is compiled. That's not the case in Udon, each line of code has an execution time.

This benchmark is mostly to show you that is is better to use builtin function instead of calculating something manually. Before implementing a function, make sure that the function hasn't already been implemented yet, you might be surprised to know how many math functions are  implemented in the Mathf or Vector3 classes!

I executed two methods Benchmark1 and Benchmark2 and compared their execution time.

private int RandomVal()
{
	return Random.Range(0, 100);
}
public override void Benchmark1()
{
	float distance;
	for (int i = 0; i < 10000; i++)
	{
		Vector3 a = new Vector3(RandomVal(), RandomVal(), RandomVal());
		Vector3 b = new Vector3(RandomVal(), RandomVal(), RandomVal());
			float num = a.x - b.x;
		float num2 = a.y - b.y;
		float num3 = a.z - b.z;
		distance = (float)System.Math.Sqrt(num * num 
			+ num2 * num2 
			+ num3 * num3);
	}
}

public override void Benchmark2()
{
	float distance;
	for (int i = 0; i < 10000; i++)
	{
		Vector3 a = new Vector3(RandomVal(), RandomVal(), RandomVal());
		Vector3 b = new Vector3(RandomVal(), RandomVal(), RandomVal());
			distance = Vector3.Distance(a,b);
	}
}

Both methods calculate distances, but the second method calls the builtin Distance method.

B1 : 166.699 ms (1.79 times slower)
B2 : 92.678 ms

Use builtin functions as much as you can!