Skip to main content

The "ref" keyword

U# now supports the "ref" keyword, which is really cool! For those who don't know what the "ref" keyword does, I'll link the C# documentation here : https://learn.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/ref

But does it affect the performance in U#?

private void FunctionRef(ref int a)
{
	a = 1;
}

private int FunctionRet(ref int a)
{
	return 1;
}

public override void Benchmark1()
{
	for (int i = 0; i < 50000; i++)
	{
		int a = 0;
      	FunctionRef(ref a);
	}
}

public override void Benchmark2()
{
	for (int i = 0; i < 50000; i++)
	{
		int a = 0;
      	a = FunctionRet();
	}
}

Both methods do the same thing, setting a variable a to 1, but the first script passes a reference.

B1 : 14.859 ms (1.04 times slower)
B2 : 14.171 ms

Good news! The difference is really negligible, you can safely use "ref" without worrying about performance impacts.