Passing one class/struct vs passing several parameters
I am wondering about performance considerations.
Would it be better performance-wise to pass into a method call a class or a struct (which?) holding two int parameters and an object reference, or would it be better to pass these three as three parameters?
Note:
I am developing on the Unity3D platform, so it’s possible some things work differently then the classical .NET
If you pass a
class, then the first thing you need to do is create an object, which will later need to be garbage collected. Not a problem normally, but on some Unity target platforms that could be undesirable if you are doing this lots.If you pass a
structnormally, then it needs to copy the struct. If it was big enough for you to be asking questions about encapsulation (i.e. representing more than a few parameters), then it is probably non-trivially big, and could be a pain to copy all the time, especially if passing down a few layers.Passing individual parameters is fairly well known, and shouldn’t cause a huge problem. Optional parameters in 4.0 can make adding more parameters less painful, but they are still passed (just with their default values).
An interesting option for unity is passing a
structby ref, since this doesn’t copy the contents (it just passes a reference to the value you created, typically on the stack), and doesn’t require any garbage collection, i.e.However, in most useful cases, I can’t see that this gains you much over just
unless of course you are passing the parameters down a few layers – in which case it has the advantage that it doesn’t need any copying. But watch out: the values are no longer independent between layers in the call-stack (regular parameters, not passed
ref, are isolated to the method).I think that at least describes some of the things to consider, but I don’t have a conclusive answer for you. If you want something more scientific, you probably need to measure.