开发者

Which of these two snippets uses more memory?

开发者 https://www.devze.com 2023-01-20 20:27 出处:网络
string Name = \"\"; for(int i; i < 10; i++) { Name = NameList[i] + \"what?\"; Console.WriteLine(Name);
string Name = "";

for(int i; i < 10; i++)
{
    Name = NameList[i] + "what?";
    Console.WriteLine(Name);
}


//Or this one:

for(int i; i < 10; i++)
{
    string Name = NameList[i] + "what?";
    Console.WriteLine(Name);
}

Which one would use less memory? Someone asked this in the comments of this question and I wasn't sure m开发者_如何学Goyself. Thanks!

Scope of variables in C#


Apart from the initial assignment in the first snippet, both snippets compile to the same IL.

The memory required is the memory for two local variables, the memory for NameList and its elements, and the memory for 10 string instances which result from concatenating the list elements with the string constant. The string instances will eventually be collected by the GC in the usual, unpredictable way. The scope of local variables has no influence on this.


In terms of actual "used" memory, assuming the compiler doesn't optimize them both to the same thing, the second could possibly use more memory, assuming the allocated memory isn't immediately garbage collected after it goes out of scope.

In terms of processing steps, again assuming the compiler doesn't fix it, the second one would take extra steps each loop to allocate memory for the string.

I generally declare variables in groups before I need them, but I think it's largely leftover paranoid behaviour from working with lower level languages.

In a larger function (which we know we should avoid), you'd technically use more memory declaring all variables up front rather than as needed (because the memory is used immediatly, not incrementally). To take it one step futher, you'd use more memory declaring all temporary variables as member variables (which is the (il)logical extension of declaring them at the beginning of a method) because they'd be allocated for an even longer lifespan.

0

精彩评论

暂无评论...
验证码 换一张
取 消