Advantages of using const instead of variables inside methods

后端 未结 8 931
北恋
北恋 2020-12-02 16:09

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

// instead of this:
var s = \"some string\";
var flags = Bindin         


        
8条回答
  •  天命终不由人
    2020-12-02 16:52

    A const value is also 'shared' between all instances of an object. It could result in lower memory usage as well.

    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 tricky in .Net and I won't pretend to understand the finer details of it, but if you instantiate a list with a million 'Static' it is likely to use considerably less memory than if you do not.

        static void Main(string[] args)
        {
            var maxSize = 1000000;
            var items = new List();
            //var items = new List();
    
            for (var i=0;i

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

提交回复
热议问题