Search code examples
c#performanceconstantsreadonly

Is there any performance benefit in using const or readonly modifiers on fields in c#?


Is there any performance benefit to using const or readonly fields compared to regular, modifiable fields, when only using private variables.

For example:

public class FooBaar
{
     private string foo = "something";
     private const string baar = "something more"

     public void Baaz()
     {
         //access foo, access baar
     }
}

In the above example you can see there are two fields: foo and baar. Both are unaccessible outside the the class, so how come many people prefer to use const here, instead of just private. Does the const provide any performance benefit?


This question was previously closed by the community, because people misunderstood this question as "What is the difference between const and readonly in terms of performance?", which has been answered here: What is the difference between const and readonly?.
But what I actually mean is, "do I get any performance benefit by using const or readonly over not using any of them".


Solution

  • I wouldn't worry too much about the performance of these constructs until you encounter a critical piece of code that requires you to make such measurements. They're there to ensure correctness of code, not for performance reasons.