Re: C# very optimisation



Helge Jensen a écrit :

I can't imagine that there is *any* difference whatsoever for the performance using ++i or i++ (esp. on integral types), and will continue to think that untill I see a test-program proving otherwise.


so try this sample code (paste in Main method) and you will think that ++i is really faster than other ways to increment by 1. (note: run in RELEASE mode)


DateTime d;
TimeSpan t;
int iMax = 1000000000;
int j;

// Test 1 : i++
j = 0;
d = DateTime.Now;
for (int i = 0; i < iMax; i++)
    j += i;
t = DateTime.Now - d;
Console.WriteLine("i++ : {0}", t.TotalMilliseconds.ToString());


// Test 2 : ++i j = 0; d = DateTime.Now; for (int i = 0; i < iMax; ++i) j += i; t = DateTime.Now - d; Console.WriteLine("++i : {0}", t.TotalMilliseconds.ToString());

// Test 3 : i += 1
j = 0;
d = DateTime.Now;
for (int i = 0; i < iMax; i += 1)
    j += i;
t = DateTime.Now - d;
Console.WriteLine("i += 1 : {0}", t.TotalMilliseconds.ToString());


// Test 4 : i = i + 1 j = 0; d = DateTime.Now; for (int i = 0; i < iMax; i = i + 1) j += i; t = DateTime.Now - d; Console.WriteLine("i = i + 1 : {0}", t.TotalMilliseconds.ToString());


Console.Read(); .


Loading