Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing one class/struct vs passing several parameters

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

like image 765
gStation Avatar asked Jan 16 '23 12:01

gStation


2 Answers

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 struct normally, 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 struct by 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.

var args = new SomeArgs(123, "abc", 23.4F, false); // <=== a struct
SomeMethod(ref args);

However, in most useful cases, I can't see that this gains you much over just

SomeMethod(123, "abc", 23.4F, false);

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.

like image 71
Marc Gravell Avatar answered Jan 31 '23 07:01

Marc Gravell


It depend on how much parameters are there.

If you have 10 parameters, it will be very difficult (readability and code management perspective) to manage it. It would be advisable to club all these parameters in a class and pass that class.

Performance point of view it will add a little overhead but its worth than passing all such parameters.

like image 24
Ram Avatar answered Jan 31 '23 08:01

Ram