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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
[STAThread] static void Main(string[] args) int Count1; int Count2; int Count3; int Count4; int Count5; int Count6; int Count7; int Count8; Count1 = Count2 = Count3 = Count4 = Count5 = Count6 = Count7 = Count8 = 100; DateTime time = DateTime.Now; for (long i = 0; i < 1000000000; i++) { int x = 100; Count1 = Count2 = Count3 = Count4 = Count5 = Count6 = Count7 = Count8 = x; } TimeSpan span = DateTime.Now - time; Console.WriteLine("Time taken{0}", span.TotalMilliseconds / 1000.0); } |
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.
Load comments