for效率测试代码:
using System; using System.Diagnostics; namespace Action { class Program { static void Main(string[] args) { GC.Collect();//清理一下先 Random ra = new Random(); int count = 1000000;//100W DateTime start = DateTime.Now; for (int i = 0; i < count; i++) { new String(""+i); } DateTime end = DateTime.Now; double usedMemory = Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0; Console.WriteLine("耗时:" + (end - start).TotalMilliseconds + "毫秒"); Console.WriteLine("消耗内存:" + usedMemory + "M"); } } }
100W次消耗时间50.88ms,消耗内存19.50M
while效率测试代码:
using System; using System.Diagnostics; namespace Action { class Program { static void Main(string[] args) { GC.Collect();//清理一下先 Random ra = new Random(); int count = 1000000;//100W DateTime start = DateTime.Now; int i = 0; while (i < count) { new String("" + i); i++; } DateTime end = DateTime.Now; double usedMemory = Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0; Console.WriteLine("耗时:" + (end - start).TotalMilliseconds + "毫秒"); Console.WriteLine("消耗内存:" + usedMemory + "M"); } } }
100W次消耗时间50.92ms,消耗内存19.59M
编码文件对比:
for:
while:
由于不能编入太多文字就只能截图了。
总结:
1、for循环与while循环效率测试上看差不多。
2、从编码上看,编译的exe文件完全相同,应该字节码是一样一样的。
3、在C#中两种循环效果相同。
单独方法编译测试:
public void forTest(){ int i; for (i = 0;i<100000000;i++){ } } public void whileTest(){ int i=0; while (i<100000000){ i++; } }
但看两端代码编译后Code都一样:【i小于100000000】
Code: stack=5, locals=4, args_size=1 0: invokestatic #2 // Method java/lang/System.currentTimeMillis:()J 3: lstore_1 4: iconst_0 5: istore_3 6: iload_3 7: ldc #3 // int 100000000 9: if_icmpge 18 12: iinc 3, 1 15: goto 6 18: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 21: invokestatic #2 // Method java/lang/System.currentTimeMillis:()J 24: lload_1 25: lsub 26: invokevirtual #5 // Method java/io/PrintStream.println:(J)V 29: return