25 January 2006

Performance and Multiple Assigment in C#

I was recently thinking if I really liked to use the Multiple assignment in ‘C#’ or if it was less readable. In ‘C’ this syntax was popular as it tended to lead to smaller and quicker code.
So I wondered in C# if the multiple assigment also lead to quicker code. So I quickly wrote some test cases to see which style of code was quicker to execute…

I took a rather simplistic model to profile, in order to make the tests more repeatable and easy to follow.

The .NET code followed the followed the structure:


Test .NET 1.1
Debug Mode
.NET 1.1
under the debugger
.NET 1.1
Release Mode
Count1=x;Count2=x;….. 7 7 4.5
Count1=Count2=Count3 …=x; 9.5 9.5 4.5
 

Results are in seconds
I did test out directly setting the values eg Count1=100; Count2=100; etc as well as using strings. These variations appeared to give similar results. I carried out the same expermiment under .NET 2 and the results were similar just slightly slower in debug mode.
The machine that carried out the tests was an Intel 3.4Ghz P4 running XP SP2 with 1GB RAM.

I guess as ever this proves that it is more important to write readable code that requires the minimum of maintanance, rather than trying to outwit the compiler/CLR.
So would I use the multiple assignment? Probably not as much as I used to, but when it leads to easier to read code then yes.

Keep up to date with Simple-Talk

For more articles like this delivered fortnightly, sign up to the Simple-Talk newsletter

This post has been viewed 2178 times – thanks for reading.

  • Rate
    [Total: 0    Average: 0/5]
  • Share

David Connell

View all articles by David Connell