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!
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.
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.
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.
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#.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With