Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a doubt regarding Memory Management in Variables declaration.

In my class i have around 20 methods, i am using around 50 variables through out my class.

I declared all variables globally at the starting of a class.

Is it the right way of doing? or else which one is better... Using structure or any thing else???

Below am showing a basic example, i need to use optimize my memory.

  class Program
    {
        static  int a, b, c, d;           //----> Here am declaring , i need any other way
        static void Main(string[] args)
        {
            a = 10;
            b = 20;
            c = 30;
            d = 40;

            int result = add(a, b, c, d);
            Console.WriteLine(result);
            Console.ReadLine();
        }
        public static int add(int w, int x, int y, int z)
        {
            return w + x + y + z;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your class-level variables are only used within a single method, so declare them only within the scope of that method:

static void Main(string[] args)
{
    var a = 10;
    var b = 20;
    var c = 30;
    var d = 40;

    int result = add(a, b, c, d);
    Console.WriteLine(result);
    Console.ReadLine();
}

As a rule of thumb, keep your variables as close to their use as possible. Any time the scope has to increase, step back and think about the structure. Don't just blindly move the variables up in scope.

Is there a reason you're trying to optimize the resource consumption of your code? Chances are, especially in a case this simple, the compiler is doing a fine job of this already. Unless you're seeing actual problems, don't prematurely optimize. More often than not this results in unmanageable code.

Also, and this is a side note because I understand that this is a contrived example... Meaningful variable names are very important. Meaningful names also help you understand and identify the desired scope of your variables. If a variable is called a then that doesn't give you any context about what it means. But if the name tells you what it means then you can more readily visualize what context in the code is actually responsible for that value, resulting in better scope definition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...