Benefits of using const instead of variables inside methods

Whenever I have local variables in a method, ReSharper suggests converting them to constants:

// instead of this: var s = "some string"; var flags = BindingFlags.Public | BindingFlags.Instance; // ReSharper suggest to use this: const string s = "some string"; const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; 

Given that these are really constant values โ€‹โ€‹(not variables), I understand that ReSharper suggests changing them to const.

But besides this, is there another advantage when using const (for example, higher performance) that justifies using const BindingFlags instead of the convenient and readable var keyword?

BTW: I just found the same question here: Resharper always suggests that I create a const string instead of a string , but I think it's more about the fields of the class where my question is about the local variable / consts.

+64
c # coding-style const resharper
Apr 29 2018-11-11T00:
source share
8 answers

The compiler will throw an error if you try to assign a value to a constant, which may prevent you from accidentally changing it.

In addition, there is usually a slight performance advantage for using constants and variables. This is due to the way they are compiled into MSIL, for this MSDN Q&A log :

Now, where myInt is referenced in the code, instead of doing "ldloc.0" to get the value from the variable, MSIL just loads the constant value, which is hard-coded into MSIL. Typically, a small performance and memory advantage is usually used to use constants. However, to use them, you must have a variable value at compile time and any references to this constant at compile time, even if they are in a different assembly, this replacement will be made.

Constants are certainly a useful tool if you know the value at compile time. If you do not, but want to make sure that your variable is set only once, you can use the readonly keyword in C # (which corresponds to initinly in MSIL) to indicate that the value of the variable can only be set in the constructor; after that, it is a mistake to change it. This is often used when the field helps determine the identity of the class and is often set equal to the constructor parameter.

+78
Apr 29 '11 at 3:26 a.m.
source share

According to my understanding, Const values โ€‹โ€‹do not exist at runtime, i.e. as a variable stored in a certain memory cell, they are embedded in the MSIL code at compile time. And therefore, it will affect performance. Moreover, at runtime it is not necessary to perform any storage operations (conversion checks / garbage collection, etc.) on them, where, since the variables require these checks.

+15
Apr 29 '11 at 15:49
source share

tl; dr for local variables with literal values, const has no meaning.




Your distinction between "internal methods" is very important. Let's look at it, and then compare it with const fields.

Constant local variables

The only advantage of the local variable const is that the value cannot be reassigned.

However, const limited to primitive types ( int , double , ...) and string , which limits its applicability.

Deviation. There are suggestions for the C # compiler to allow the more general concept of "readonly" locals ( here ), which will extend this advantage to other scripts. They probably won't be considered const , and probably will have a different keyword for such declarations (like let or readonly var or something like that).

Consider these two methods:

 private static string LocalVarString() { var s = "hello"; return s; } private static string LocalConstString() { const string s = "hello"; return s; } 

In Release mode, we see the following (abbreviated) IL:

 .method private hidebysig static string LocalVarString() cil managed { ldstr "hello" ret } .method private hidebysig static string LocalConstString() cil managed { ldstr "hello" ret } 

As you can see, both of them produce the same IL. Regardless of whether local s const or not, this does not affect.

The same is true for primitive types. Here is an example of using int :

 private static int LocalVarInt() { var i = 1234; return i; } private static int LocalConstInt() { const int i = 1234; return i; } 

And again, IL:

 .method private hidebysig static int32 LocalVarInt() cil managed { ldc.i4 1234 ret } .method private hidebysig static int32 LocalConstInt() cil managed { ldc.i4 1234 ret } 

Therefore, again we do not see the difference. There can be no performance or memory. The only difference is that the developer cannot reassign the character.

Fields Const

Comparison of const field with variable field is different. Non-console field must be read at runtime. So, you end up with IL:

 // Load a const field ldc.i4 1234 // Load a non-const field ldsfld int32 MyProject.MyClass::_myInt 

Clearly, this could make a difference in performance, assuming JIT cannot embed a constant value.

Another important difference here is the public constant fields that are shared between assemblies. If one assembly provides a const field and the other uses it, then the actual value of this field is copied at compile time. This means that if the assembly containing the const field is updated, but the assembly is not compiled, then the old (and possibly incorrect) value will be used.

+7
Mar 11 '18 at 20:35
source share

const is a compile-time constant - this means that all of your code that uses the const variable is compiled to contain a constant expression containing a constant variable - the emitted IL will contain this constant value.

This means that the memory size is smaller for your method, because the constant does not require any memory allocation at runtime.

+4
Apr 29 2018-11-21T00:
source share

The value of const is also "shared" between all instances of the object. This may result in reduced memory usage.

As an example:

 public class NonStatic { int one = 1; int two = 2; int three = 3; int four = 4; int five = 5; int six = 6; int seven = 7; int eight = 8; int nine = 9; int ten = 10; } public class Static { static int one = 1; static int two = 2; static int three = 3; static int four = 4; static int five = 5; static int six = 6; static int seven = 7; static int eight = 8; static int nine = 9; static int ten = 10; } 

Memory consumption is complicated. Net, and I will not pretend to understand its finer details, but if you create a list with a million "Static", it will probably use significantly less memory than if you did not.

  static void Main(string[] args) { var maxSize = 1000000; var items = new List<NonStatic>(); //var items = new List<Static>(); for (var i=0;i<maxSize;i++) { items.Add(new NonStatic()); //items.Add(new Static()); } Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().WorkingSet64); Console.Read(); } 

When using NonStatic, the working set is 69,398,528 compared to 32,423,936 when using static electricity.

+2
Apr 29 '11 at 3:26 a.m.
source share

Besides a slight performance improvement, when you declare a constant, you explicitly apply two rules for yourself and other developers who will use your code

  • I need to initialize it with a value right now, I cannot do it elsewhere.
  • I canโ€™t change its meaning anywhere.

The code has all its readability and communication.

+2
Apr 29 '11 at 16:07
source share

The const keyword tells the compiler that it can be fully evaluated at compile time. There is a performance and memory advantage for this, but it is small.

+1
Apr 29 2018-11-11T00:
source share

Constants in C # provide a name with a name in memory to store the value of the data. This means that the value of the variable will be known at compile time and will be stored in one place.

When you declare it, it is "hard-coded" in the Microsoft Intermediate Language (MSIL).

Although this is a bit, it can improve the performance of your code. If I declare a variable and I can make it a constant, I always do it. Not only because it can improve performance, but also because the idea of โ€‹โ€‹constants. Otherwise, why do they exist?

A reflector can be really useful in situations like this. Try declaring a variable, and then make it a constant and see what code is generated in IL . Then all you have to do is see the difference in instructions and see what these instructions mean.

+1
Apr 29 '11 at 15:34
source share



All Articles