In my project I am looping across a dataview result.
string html =string.empty;
DataView dV = data.DefaultView;
for(int i=0;i< dV.Count;i++)
{
DataRowView rv = dV[i];
html += rv.Row["X"].Tostring();
}
Number of rows in dV will alway be 3 or 4.
Is it better to use the string concat += opearator or StringBuilder for this case and why?
I would use
StringBuilderhere, just because it describes what you’re doing.For a simple concatenation of 3 or 4 strings, it probably won’t make any significant difference, and string concatenation may even be slightly faster – but if you’re wrong and there are lots of rows,
StringBuilderwill start getting much more efficient, and it’s always more descriptive of what you’re doing.Alternatively, use something like:
Note that you don’t have any sort of separator between the strings at the moment. Are you sure that’s what you want? (Also note that your code doesn’t make a lot of sense at the moment – you’re not using
iin the loop. Why?)I have an article about string concatenation which goes into more detail about why it’s worth using
StringBuilderand when.EDIT: For those who doubt that string concatenation can be faster, here’s a test – with deliberately “nasty” data, but just to prove it’s possible:
Results on my machine (compiled with
/o+ /debug-):I’ve run this several times, including reversing the order of the tests, and the results are consistent.