我在 C# 中对使用 For 循环和 While 循环对 ArrayList 进行比较搜索进行了一些性能测试。
它似乎具有二次时间消耗。
但是,如果我使用LastIndexOf
或IndexOf
搜索列表,它会获得“比预期更快”的速度。
有谁知道原因?
我在 C# 中对使用 For 循环和 While 循环对 ArrayList 进行比较搜索进行了一些性能测试。
它似乎具有二次时间消耗。
但是,如果我使用LastIndexOf
或IndexOf
搜索列表,它会获得“比预期更快”的速度。
有谁知道原因?
Use ILSpy and take a look at the internals of LastIndexOf/IndexOf methods. There lies your answer as to why they are faster.
I have a hunch that the List internally uses a B-tree or some other tree, which has a lookup of log(n). What you are doing with for/foreach is performing a linear lookup with some extra overhead. If you remember your maths class then you'd know that log(n) is flatter than a linear line, thus having faster lookup...
我不知道任何C#,但我可以提出可能的答案。
任何编程语言方法通常都以利用它们运行的处理器提供的快捷方式的方式编写 - 您自己编写的代码不会(例如,您必须声明必须保留在堆栈中的局部变量,需要较慢的查找时间,而不仅仅是一个临时寄存器变量)。因此,语言本身所做的任何事情通常都会比您自己的代码更快。