EDIT: The dis assembly of both cases are also attached based on given comment through Tools > Options > Debugging > 'Suppress JIT optimization on module load' > uncheck (clear this option, to do JIT Optimization even in debug mode). It can be seen that the generated machine code is not good when pseudo codes are available! in fast version, the code use CPU Registers directly but in other version, it load p1.x and p1.y from memory in every iteration! i don't know how could we control such behavior!
When i was trying to measure execution time of a block of code for performance testing, i found some irregularities that confused me: if i add some block of (pseudo) code before the actual measuring loop, the total elapsed time is increased by a large factor (from 120 msec to 220 msec i.e. about 1.8 times slower! in my 2 GHz PC). Note that in real case, these pseudo codes are some different codes required for initialization or similar purposes.
NOTE: I build the app in Release Mode and run it by Start Without Debug (Ctrl+F5) to ensure all optimizations are applied to get best results.
I show a simplified scenario here as sample:
void test()
{
Point p1 = new Point(1, 2);
Point p = p1;
//*** !!! Comment & UnComment the following 2 lines to see difference: ***
p.Offset(p1); p.Offset(p1); p.Offset(p1); p.Offset(p1);
p.Offset(p1); p.Offset(p1); p.Offset(p1); p.Offset(p1);
Stopwatch timer = new Stopwatch();
double dt = -1;
for (int repeat = 1; repeat <= 5; repeat++)
{
p = p1; //here we reset the initial p
timer.Restart();
for (int i = 0; i < 50000000; i++)
{
p.Offset(p1);
}
timer.Stop();
dt = timer.ElapsedMilliseconds;
textBox1.Text += repeat + "] " + dt + ", p: " + p + "\r\n";
Application.DoEvents(); if (this.IsDisposed) break;
}
}
private void button1_Click(object sender, EventArgs e)
{
test();
}
This issue prevents me from comparison of results i need for optimization.
By the way, this may relates to struct
types(?).
Do you know what is the reason and how to solve it?
EDIT (4 Apr.): i checked and found that this behavior is only happen for struct
types not class
types. and as we know, structs are usually value types in Stack rather than heap. this may have a role here but i don't know..
Another Note: i also found that if i uncheck the 'Optimize Code' option in project Properties > Build tab, then the code actually runs faster!