I've got a small structure and have found that copying the individual members is substantially faster than copying the structure in one go. Is there a good reason for this?
My program:
// Some random structure
private struct PackStats
{
public int nGoodPacks, nBadPacks, nTotalPacks;
}
// ...
PackStats stats1 = new PackStats();
PackStats stats2 = new PackStats();
// Set some random statistics
stats1.nGoodPacks = 55;
stats1.nBadPacks = 3;
stats1.nTotalPacks = (stats1.nGoodPacks + stats1.nBadPacks);
// Now assign stats2 from stats1
// This single line consumes ~190ns...
stats2 = stats1;
// ...but these three lines consume ~100ns (in total)
stats2.nGoodPacks = stats1.nGoodPacks;
stats2.nBadPacks = stats1.nBadPacks;
stats2.nTotalPacks = stats1.nTotalPacks;
To measure times in the nanosecond range, I make the assignments millions of times:
uint uStart = GetTickCount();
for (int nLoop=0; nLoop<10000000; nLoop++)
{
// Do something...
}
uint uElapsed = (GetTickCount() - uStart);
The results were roughly consistent with both optimisation enabled and disabled...copying individual members of this small structure was about twice as fast. Would the same result apply in C/C++?