【发布时间】:2018-02-03 03:19:54
【问题描述】:
using System.Collections.Generic;
using System.IO
哪个变种更快?
这个?
List<short> a = new List<short>();
a.Add(0);
a.Add(1);
a.Add(2);
FileStream fs = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Write){
using ( BinaryWriter bw = new BinaryWriter(fs)){
foreach ( short b in a ){
bw.Write(b);
}
}
}
还是这个?
string a = "";
a += "0";
a += "1";
a += "2";
File.WriteAllText("file", a);
还是这个?
short[] a = new short[3];
a[0] = 0;
a[1] = 1;
a[2] = 2;
FileStream fs = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Write){
using ( BinaryWriter bw = new BinaryWriter(fs)){
foreach ( short b in a ){
bw.Write(b);
}
}
}
我想知道每段代码的编译速度,以及我如何自己测量速度。
【问题讨论】:
-
如果您对执行时间感兴趣,那么可以使用StopWatch 进行测量。
-
HashSet 之类的类被记录为在 O(1) 时间内执行。这记录在 msdn 上。但是像你提到的那些普通方法没有这样的时间规范。您需要自己进行基准测试。只需在所有情况下创建相同的场景。例如,运行该过程 10000 次。确保在开始时启动计时器并在重复 10000 次后打印出时间。然后比较场景之间的时间并重复 2 到 4 次以消除可能的临时性能问题。
-
每段代码编译的速度有多快——好吧,这段代码编译的速度有多快真的很重要吗?
-
第一个更快,而不是第二个....因为很明显,short 比字符串需要更少的编译时间,所以第一种情况
标签: c# .net arrays string list