最近,我一直在研究一些编写返回集合的函数的约定。我想知道实际上使用a的函数是否List<int>应该返回a List<int>或宁可IList<int>是ICollection<int>or IEnumerable<int>。我创建了一些性能测试,结果令我非常惊讶。
static List<int> list = MakeList();
static IList<int> iList = MakeList();
static ICollection<int> iCollection = MakeList();
static IEnumerable<int> iEnumerable = MakeList();
public static TimeSpan Measure(Action f)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
f();
stopWatch.Stop();
return stopWatch.Elapsed;
}
public static List<int> MakeList()
{
var list = new List<int>();
for (int i = 0; i < 100; ++i)
{
list.Add(i);
}
return list;
}
public static void Main()
{
var time1 …Run Code Online (Sandbox Code Playgroud) 在 Unity 中,我有一个脚本,我在其中通过 TCP 连接到套接字,并希望在每一帧都使用此连接。之后我需要处理和清理。我的想法是用来Start()开始连接和OnDestroy()
public class Foo : MonoBehaviour
{
void Start()
{
// start TCP connection
}
void Update()
{
// use connection
}
void OnDestroy()
{
// cleanup
}
}
Run Code Online (Sandbox Code Playgroud)
我需要清理来执行任何发生的事情。OnDestroy()无论对象发生什么情况,该方法是否保证在应用程序停止之前(在独立模式和编辑器中)被调用?如果没有,我如何保证清理?
使用yield关键字,我们只能计算中所需的项目数量IEnumerable。我已经建立了一个测试,其中我生成了许多项目,然后又想生成一个项目。我期望的是该函数从其结束处开始,在这种情况下是在10000000迭代中,仅再次迭代到10000001。请检查这段代码:
public static void Main()
{
var naturalNumbers = GetNaturalNumbers();
var executionTime = GetExecutionTime(() => naturalNumbers.ElementAt(10000000));
Console.WriteLine($"Time elapsed: {executionTime}");
executionTime = GetExecutionTime(() => naturalNumbers.ElementAt(10000001));
Console.WriteLine($"Time elapsed: {executionTime}");
}
public static IEnumerable<int> GetNaturalNumbers()
{
Console.WriteLine("Running GetNaturalNumbers() from the beginning");
for(int value = 0;; value++)
{
yield return value;
}
}
public static System.TimeSpan GetExecutionTime(Action action)
{
var stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Running GetNaturalNumbers() from the beginning
Time elapsed: …Run Code Online (Sandbox Code Playgroud)