偶然想到的一个问题。。。
今天突然想C#中,用数组中的Max()方法和直接通过比较获取最大值的时间谁快,于是试了试:
static void Main(string[] args)
{
Random random = new Random();
int[] arr = new int[100000000];
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
arr[i] = random.Next();
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int a = arr.Max();
stopwatch.Stop();
double t = stopwatch.Elapsed.TotalSeconds;
stopwatch.Restart();
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] >= temp)
{
temp = arr[i];
}
}
stopwatch.Stop();
double t2 = stopwatch.Elapsed.TotalSeconds;
Console.WriteLine(a);
Console.WriteLine(temp);
Console.WriteLine("Max方法时间:" + t);
Console.WriteLine("比较时间:" + t2);
Console.ReadKey();
}结果是这样的:
看起来是比较快些。。。




鲁公网安备 37148202000241号