In C# we can specify in
on struct method parameters so that they are passed as readonly references:
public int TimesTwo(in int number)
{
return number * 2;
}
This is almost the same as using ref
but does not allow modifications to the parameter:
public int TimesTwo(in int number)
{
number *= 2; // Compiler error
return number;
}
Additionally it does not require specifying the keyword when calling, like ref
does:
var x = 1;
var y = TimesTwo(x);
var z = TimesTwo(in x);
// y and z are both 2
In some scenarios this is not possible, like when you need to modify the parameter or with async or iterator methods which do not allow in
. But the question is, in 99% of cases where the parameter is only read then why not specify in
?
When in
is not specified, the parameter passed is copied to a local variable. This copying can take time that can be noticeable for large structs in tight loops, as Microsoft says here.
With in
, the reference is passed, so no copying takes place. Maybe the time saved not copying is negligible in most cases, but I want to know if there is any reason other than the standard "it clutters the code" or "it's a micro-optimization you shouldn't be worrying about".
As far as I can tell this "micro-optimization" of bypassing struct copying is exactly why in
was introduced. Are there other reasons why this would be bad practice to just throw it in everywhere for performance critical code?