Is there any performance advantage when using const or readonly modifiers in fields in C #?

Is there a performance advantage when using const or readonly fields compared to regular, modifiable fields when only private variables are used.

For instance:

 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 that there are two fields: foo and baar . Both are inaccessible outside the class, therefore, as many people prefer to use const here, rather than just private . Does const provide any performance advantage?


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 was answered here: What is the difference between constant and readonly? .
But actually, I mean: "I get any performance benefit using const or readonly without using any of them."

+6
source share
2 answers

I would not worry too much about the performance of these constructs until you come across a critical piece of code that requires you to take such measurements. They are there to ensure that the code is correct, and not for performance reasons.

+6
source

A const will be optimized by the compiler, which will be embedded in your code, but cannot be embedded in readonly. However, you cannot create constants of all types, so here you should make them read-only.

So, if you need a constant value in your code, you should first use a constant, if possible, if not then read only, so that you can have security, but not efficiency.

As an example:

 public class Example { private const int foo = 5; private readonly Dictionary<int, string> bar = new Dictionary<int, string>(); //.... missing stuff where bar is populated public void DoSomething() { Console.Writeline(bar[foo]); // when compiled the above line is replaced with Console.Writeline(bar[5]); // because at compile time the compiler can replace foo with 5 // but it can't do anything inline with bar itself, as it is readonly // not a const, so cannot benefit from the optimization } } 
+11
source

Source: https://habr.com/ru/post/894187/


All Articles