General Performance Tip: Constant vs Variable

Updated March 2024

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

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

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

This is the same example using a constant.

public class CircleCalculator
{
      public const double PI = 3.1415926535897932384626433832;
}

Benchmark Results

This benchmark illustrates that employing a constant is 3.2 times faster than utilizing a variable!

My recommendation is to use constants where appropriate. This shows the intent of the variable.
This is related to violation CA1802 and this is how I have it setup in my EditorConfig: dotnet_diagnostic.CA1802.severity = warning

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

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

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 preproduced in any way without express permission from David McCarter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.