循环20000*20000次,执行20次,来确定2种循环的速度for循环 Int32[] n = new Int32[20000];
Int64 sum = 0;
for (Int32 temp = 0; temp < 20; temp++)
{
DateTime start = DateTime.Now;
for (Int32 i = 0; i < n.Length; i++)
{
for (Int32 j = 0; j < n.Length; j++)
{ }
}
sum += DateTime.Now.Ticks - start.Ticks;
Console.WriteLine(DateTime.Now.Ticks - start.Ticks);
}
Console.WriteLine("平均:"+sum/20);
}
foreach循环 Int32[] n = new Int32[20000];
Int64 sum = 0;
for (Int32 temp = 0; temp < 20; temp++)
{
DateTime start = DateTime.Now;
foreach (Int32 i in n)
{
foreach (Int32 j in n)
{ }
}
sum += DateTime.Now.Ticks - start.Ticks;
Console.WriteLine(DateTime.Now.Ticks - start.Ticks);
}
Console.WriteLine("平均:"+sum/20);
}
结果是
foreach平均花28023437毫秒
for 平均花22000000毫秒
Int64 sum = 0;
for (Int32 temp = 0; temp < 20; temp++)
{
DateTime start = DateTime.Now;
for (Int32 i = 0; i < n.Length; i++)
{
for (Int32 j = 0; j < n.Length; j++)
{ }
}
sum += DateTime.Now.Ticks - start.Ticks;
Console.WriteLine(DateTime.Now.Ticks - start.Ticks);
}
Console.WriteLine("平均:"+sum/20);
}
foreach循环 Int32[] n = new Int32[20000];
Int64 sum = 0;
for (Int32 temp = 0; temp < 20; temp++)
{
DateTime start = DateTime.Now;
foreach (Int32 i in n)
{
foreach (Int32 j in n)
{ }
}
sum += DateTime.Now.Ticks - start.Ticks;
Console.WriteLine(DateTime.Now.Ticks - start.Ticks);
}
Console.WriteLine("平均:"+sum/20);
}
结果是
foreach平均花28023437毫秒
for 平均花22000000毫秒
for 是用来循环数组
应该测试多种数据类型
QQ351091855
在我的机器上测试是 foreach 更快:using System;class A
{
static void Main()
{
For();
Foreach();
}
static void For()
{
Int32[] n = new Int32[20000];
Int64 sum = 0;
for (Int32 temp = 0; temp < 20; temp++)
{
DateTime start = DateTime.Now;
for (Int32 i = 0; i < n.Length; i++)
{
for (Int32 j = 0; j < n.Length; j++)
{
}
}
sum += DateTime.Now.Ticks - start.Ticks;
}
Console.WriteLine("for 平均: {0:N0}", sum/20);
} static void Foreach()
{
Int32[] n = new Int32[20000];
Int64 sum = 0;
for (Int32 temp = 0; temp < 20; temp++)
{
DateTime start = DateTime.Now;
foreach (Int32 i in n)
{
foreach (Int32 j in n)
{
}
}
sum += DateTime.Now.Ticks - start.Ticks;
}
Console.WriteLine("Foreach平均: {0:N0}", sum/20);
}
}
/* 程序输出:
for 平均: 4,671,875
Foreach平均: 4,492,187
*/
for 平均: 14,257,812
Foreach平均: 18,250,000Foreach平均: 18,250,000
for 平均: 14,234,375Foreach平均: 18,273,437
for 平均: 14,234,375