我相信寫代碼的人對i++和++i都不陌生,但你完全搞懂這兩種寫法了嗎?下面說明一下他們的區別。簡單地說,i++ 是先用再加,++i 是先加再用。
1 int i = 0;
2 int y = 1;
3 y = i++;
4 Console.WriteLine("y的值為:{0}", y.ToString());
5 Console.WriteLine("i的值為:{0}", i.ToString());
上面的代碼運行結果:

下面再看一段代碼:
1 int i = 0;
2 Console.WriteLine("先引用,後運算,所以 i 還是{0}", (i++).ToString());
3 Console.WriteLine("現在 i 在內存中的值為{0}", i.ToString());
4 Console.WriteLine("先運算,後引用,所以 i 的值為{0}", (++i).ToString());
5 Console.ReadLine();
這段代碼運行結果:

我們在for循環中經常用到i++,那麼在for循環中i++和++i有什麼區別呢?繼續看代碼:
1 var count = 0;
2 for (int i = 1; i <= 10; i++)
3 {
4 count += 1;
5 }
6 Console.WriteLine("循環次數為:{0}", count.ToString());
7 Console.ReadLine();
運行結果:

把for循環中的i++換成++i呢?看代碼:
1 var count = 0;
2 for (int i = 1; i <= 10; ++i)
3 {
4 count +=1;
5 }
6 Console.WriteLine("循環次數為:{0}", count.ToString());
7 Console.ReadLine();
運行結果:

可見對於for循環的循環次數來說,i++和++i的循環次數是一樣的,但是從性能上來講,二者有無區別呢?繼續看代碼:
1 Stopwatch sw = Stopwatch.StartNew();
2 //string count = string.Empty;
3
4 //long ticks;
5 for (int i = 1; i <= 100; i++)
6 {
7 //count = i.ToString();
8 }
9 sw.Stop();
10 var elapsed = sw.Elapsed;
11 //Console.WriteLine("循環次數為:{0}", count.ToString());
12 Console.WriteLine("耗時:{0}", elapsed.ToString());
13 Console.ReadLine();
運行結果:

把i++換成++i,其他不變,運行結果如下:

for循環100次,循環中不做任何事情,從筆者的電腦上的運行結果上看,i++比++i好,現在把循環次數改為10000000(1000萬)次,結果如何呢?


如果在for循環中加入某些事務邏輯呢?代碼改為:
1 Stopwatch sw = Stopwatch.StartNew();
2 string count = string.Empty;
3
4 //long ticks;
5 for (int i = 1; i <= 100; i++)
6 {
7 count = i.ToString();
8 }
9 sw.Stop();
10 var elapsed = sw.Elapsed;
11 Console.WriteLine("循環次數為:{0}", count.ToString());
12 Console.WriteLine("耗時:{0}", elapsed.ToString());
13 Console.ReadLine();
先測試循環次數為100的結果:
i++如下:

++i如下:

將循環次數改為1000萬次:
i++如下:

++i如下:

從性能上來講,i++和++i差別不大,基本在同一數量級,在for循環中一般用i++即可。