Har
Har

Reputation: 5004

C# foreach memory cache and string memory optimization

foreach (string sn in MACOrSerial.Split(','))
{
    MACOrSerial = sn.Trim();   
}

MACORSerial contains a string of text (EX. AA123241, BB123431, CC1231243) separated by commas. I grab one substring and place that into the same MACORSerial.

This will not cause me any problems as the the foreach still will be using the original MACOrSerial in memory.

While I think this is the most memory efficient approach, is it proper or should I just make another string with a new name such as

MacORSerialSubString = sn.Trim()?

I am not having any memory issues. I just want to make sure my code is clean and concise.

Upvotes: 1

Views: 1114

Answers (5)

Chris Shain
Chris Shain

Reputation: 51339

My $.02- the code as you posted is extremely un-intuitive, because it breaks with the expected pattern.

IMHO it is more important to write the code in a way that other developers can understand at a glance than it is to (actually / attempt to) micro-optimize for memory, especially when (as others have pointed out) your micro-optimization does not actually reduce the amount of memory used.

Upvotes: 4

Oded
Oded

Reputation: 499062

Your assumption is incorrect - the loop goes over the string[] resulting from the Split - these are all new string instances.

You are not saving any memory by reassigning a string to the original variable and you are losing readability by reuse of a variable.

Here is one approach that is more readable and uses some of the built in capabilities:

string[] serialNumbers = MACOrSerial.Split(new [] {',', ' ', '\r', '\n' }, 
                                   StringSplitOptions.RemoveEmptyEntries);

foreach (string sn in serialNumbers)
{
    // do stuff
}

Upvotes: 8

user1222021
user1222021

Reputation:

In reality, your iteration will be using the result of the MACOrSerial.Split() call, which is an array that is independent from the MACOrSerial variable.

There will be no difference between using MACOrSerial or another string variable in terms of memory usage, each time sn.Trim() is called, a new string is generated and it's just the reference to this new string that gets placed in your string variable.

Upvotes: 1

mgnoonan
mgnoonan

Reputation: 7200

For clarity (and later maintaining) of the code, I would prefer use of a separate variable. Plus I would remove the empty strings up front:

foreach (string sn in MACOrSerial.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
    string MacORSerialSubString = sn.Trim();
} 

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190941

I would create a new variable so that your code is more clear. It doesn't have any noticable impact on memory.

Upvotes: 2

Related Questions