Question

Which is the most efficient & which is (subjectively) the most readable? (Another developer wrote the second option and I want to be sure I have a good reason for changing it to match the first option below)

Pen pen = Pens.Red;
if (highlight)
    pen = new Pen(Color.Red, 3.0f);

or

Pen pen;
if (highlight)
    pen = new Pen(Color.Red, 3.0f);
else
    pen = Pens.Red;

I know that it makes a marginal difference, but I have a draw algorithm that needs to be literally as fast as possible! so every little bit helps. And no, using another language to handle the drawing is not an option at this point.

Thanks for the help!

Was it helpful?

Solution

var pen = highlight ? highlightPen : Pens.Red;


static readonly Pen highlightPen = new Pen(Color.Red, 3.0f);

OTHER TIPS

There is no issue with "performance" here: if a performance issue is suspected then benchmark, benchmark, benchmark (in a real usage scenario) and see.

In any case, my preference is:

var pen = highlight
  ? new Pen(Color.Red, 3.0f)
  : Pens.Red;

But out of the two above, I prefer the one without the default value, but not for "performance": I do so because then the C# compiler can then be relied upon to ensure that at least one of the value-setting paths is executed (or it will throw a compilation error about the use of an unassigned local variable).

(And yes, while this same holds true for the case with an initial value assigned, it breaks down for more complex situations where it is desirable to ensure that one of the paths of execution actually executes. Thus I choose consistency, where practical.)

Happy coding!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top