What I have read, passing arguments is by default valuetypes. In my example the first function test1 takes a reference type and unbox, it will decrease the performance if I got this right.
However I have never read that you do like test2 for increase performance.
So whats best practice?
public Main(){
string test = "hello";
test1(test); // Does this line perform a boxing? So it's not good for performance?
test2(ref test); // Passing a reference as a reference
}
public string test1(string arg1) {
return arg1;
}
public string test2(ref string arg1) {
return arg1;
}
There’s no boxing or unboxing involved at all here.
stringis a reference type – why would it be boxed? What would that even mean?Even if you used
intinstead, there’d be no need for boxing, because there’s no conversion of the value into an actual object.I suspect your understanding of both boxing and parameter passing is flawed.
Boxing occurs when a value type value needs to be converted into an object, usually in order for it to be used as a variable (somewhere) of an interface or object type. So this boxes:
… but it wouldn’t occur if
Foowere changed such that the type ofxwereintinstead.The detailed rules on boxing become very complicated to state precisely and accurately, particularly where generics come in, but that’s the basics.