Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there performance penalties for named/optional parameters for constructors? [duplicate]

So would:

public Car(string color = "red", topSpeed = 180)
{
  carColor = color;
  carTopSpeed = topSpeed;
}

be faster or slower to do than constructor chaining to get the values to carColor and carTopSpeed? I understand on a desktop environment the performance will almost always be negligible, but:

I would like to know for mobile game development where all the little things count in performance.

Thanks in advance!

like image 910
Kites Avatar asked Feb 27 '14 07:02

Kites


People also ask

Are optional parameters bad practice?

The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.

Is it better to use named or unnamed parameters in C#?

The main advantage of named arguments in C# is that we can pass the arguments out of their positional order. Simply put, we don't have to remember the order of parameters. They also increase the readability of the application, especially in cases where all the arguments are of the same type.

Should we use optional parameter?

It depends on what your code is doing. If there are sensible defaults then you should use optional parameters but if there are no sensible defaults then adding optional parameters will make your code more complicated.

Can we have multiple optional parameters in C#?

In c#, we can also achieve the optional parameters by using method overloading functionality. Generally, the method overloading functionality will allow us to create multiple methods with the same name but with different parameters. To know more about overloading functionality in c#, check Method Overloading in C#.


1 Answers

No performance penalties.

In fact, optional parameters do not exist at runtime. They are a compiler trick, i.e. the compiler puts in the full parameter set.

There even is an explicit warning to not use them (one I totally disagree with) because if you change the default value, then the old compiled code does not use the new values.

Performance differences between overloading or optional parameters?

has exactlyx the same question.

like image 124
TomTom Avatar answered Oct 21 '22 21:10

TomTom