Your timings seem to be for debug builds. I did the same test with this code:
private void DoIt() { const int numReps = 1000000000; PackStats stats1 = new PackStats(); PackStats stats2 = new PackStats(); stats1.a = 55; stats1.b = 3; stats1.c = stats1.a + stats1.b; for (var i = 0; i < 2; ++i) { var sw1 = Stopwatch.StartNew(); for (var j = 0; j < numReps; ++j) { stats2 = stats1; } sw1.Stop(); Console.WriteLine("Copy struct = {0:N0} ms", sw1.ElapsedMilliseconds); sw1.Restart(); for (var j = 0; j < numReps; ++j) { stats2.a = stats1.a; stats2.b = stats1.b; stats2.c = stats1.c; } sw1.Stop(); Console.WriteLine("Copy fields = {0:N0} ms", sw1.ElapsedMilliseconds); } }
My timings are shown below:
struct fields Debug/Debug 2,245 1,908 Debug/No 2,238 1,919 Release/Debug 287 294 Release/No 281 275
This is with Visual Studio 2015. The program is compiled like any processor and runs on a 64-bit machine.
Debugging / Debugging means running the debug build with the debugger attached (i.e. press F5 to start the program). Debugging / No means that debugging starts without debugging (i.e. Ctrl + F5). And Release, of course, means building a release.
What this tells me is that in release mode there is virtually no difference between copying a structure at once or copying individual fields. In the worst case shown here, it's 6 milliseconds over a billion iterations.
The answer to your question: "Copy individual members faster than the whole structure?" It appears "In debug mode, yes."
source share