General Performance: Constant vs Variable

When including numerical or string values in code that remain static, it is advisable to transform them into constants.

This is an example using a constant for π.

public class CircleCalculator
{
    private readnly double _pi = 3.1415926535897932384626433832;
}

This is an example of exposing the value of π through a read-only property.

public class CircleCalculator
{
  private double _pi = 3.1415926535897932384626433832;

  public double PI => _pi;
}

Performance Breakdown

The benchmark reveals that both show the same performance, which is different from past versions of .NET.

My recommendation is to use constants where appropriate. This shows the intent of the variable.

When I set up my EditorConfig to check for this issue, it looks like this:
dotnet_diagnostic.CA1802.severity = suggestion

Always benchmark any changes using tools like BenchmarkDotNet to ensure your optimizations result in measurable improvements in your actual codebase.

To analyze your code using the same settings I used in these articles, I encourage you to incorporate my EditorConfig file. It can be found at the following link: https://bit.ly/dotNetDaveEditorConfig.

Please feel free to leave a comment below. I would appreciate hearing your thoughts and feedback.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply