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.

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


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

David Connell is a Software Developer who led the team that created the SQL Data Generator at Red-Gate. Before then, he led the 'SQL Toolbelt' installer and the SQL Doc team, and before that worked in the SQL Bundle 5.0 team. He was previously a Senior Software engineer at Pi Research. In his spare time David Connell develops other software packages with a Dutch Company, Thermimport Quality Control.

View all articles by David Connell