7

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!

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Kites
  • 83
  • 6

2 Answers2

7

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.

pim
  • 12,019
  • 6
  • 66
  • 69
TomTom
  • 61,059
  • 10
  • 88
  • 148
1

No, there is no performance penalty at all. When the compiler recognizes you're using a constructor with default parameters it automatically inserts those values into the compiled code.

Calling var car = new Car() is compiled exactly as if you called it this way:

var car = new Car("red", 180);
Enigmativity
  • 113,464
  • 11
  • 89
  • 172