Below is the code i am using
private void TestFunction()
{
foreach (MySampleClass c in dictSampleClass)
{
String sText = c.VAR1 + c.VAR2 + c.VAR3
PerformSomeTask(sText,c.VAR4);
}
}
My friend has suggesed to change to (to improve performance. dictSampleClass is a dictionary. It has 10K objects)
private void TestFunction()
{
String sText="";
foreach (MySampleClass c in dictSampleClass)
{
sText = c.VAR1 + c.VAR2 + c.VAR3
PerformSomeTask(sText,c.VAR4);
}
}
My Question is, “Does above change improve performance? if yes, how?”
WOW thats more than expected response. Most guys said “C# compiler would take care of that”. So what about c compiler??
The compiler has intelligence to move variable declarations into/out of loops where required. In your example however, you are using a string, which is immutable. By declaring it outside I believe you are trying to “create once, use many”, however strings are created each time they are modified so you can’t achieve that.
Not to sound harse, but this is a premature optimisation, and likely a failing one – due to string immutability.
If the collection is large, go down the route of appending many strings into a StringBuilder – separated by a delimiter. Then split the string on this delimiter and iterate the array to add them, instead of concatenating them and adding them in one loop.
I infer no benefits to using this code – most likely doesn’t even work!
UPDATE: in light of the fast performance of string creation from multiple strings, if PerformSomeTask is your bottleneck, try to break the iteration of the strings into multiple threads – it won’t improve the efficiency of the code but you’ll be able to utilise multiple cores.