aod aod - 11 months ago 43
C# Question

Which is more preferable? Performance or Memory while spliting a string in C#?

I would like to ask that which case of the two below is more preferable than the other considering garbage collection, memory and cpu usage in C#.

a = data.Split('|')[0];
b = data.Split('|')[1];
c = data.Split('|')[2];
d = data.Split('|')[3];
e = data.Split('|')[4];


string[] splitedData = data.Split('|');

a= splitedData[0];
b = splitedData[1];
c = splitedData[2];
d = splitedData[3];
e = splitedData[4];

I would prefer the second one since I think holding the splited data array reference and accessing from using that reference is less cpu-intensive and uses less memory access.

The first one uses more cpu and creates an array at each time (filling and accessing the array requires also more memory operation) in order to get the data accordingly.

I am asking this question because I saw in a game project created by Chupamobile that the first one was used.

Thanks in advance.

Answer Source

There's no reason to do a computation that has the same result multiple times, especially if it involves memory allocations. You're correct in that your first snippet has worse time and memory performance.

Every call to split will iterate over the string (probably the fastest part of all that), allocate two new arrays and copy a lot of substrings around. For operations such as this you should always store the result instead of making two calls.

Technically even property accesses can be stored with a very minor performance gain, but most of the time you shouldn't bother unless in situations like above.