C# For Loop、While Loop、LastIndexOf、IndexOf,为什么最后两个更快?

发布于 2024-12-09 09:05:22 字数 187 浏览 1 评论 0原文

我在 C# 中使用 For 循环和 While 循环对 ArrayList 进行比较搜索进行了一些性能测试。

它似乎有二次方的时间消耗。

但是,如果我使用 LastIndexOfIndexOf 来搜索列表,它会获得“比预期更快”的速度。

有谁知道原因吗?

I have done some performance testing in C# on using the For Loop and the While Loop for an ArrayList to do comparison search.

It seems to be having quadratic time consumption.

However, if I use LastIndexOf or IndexOf to search through the list, it gains "faster than anticipated" speed.

Does anyone know the reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鲜肉鲜肉永远不皱 2024-12-16 09:05:22

我不懂 C#,但我可以提出可能的答案。

任何编程语言方法通常都是利用它们运行的​​处理器提供的快捷方式编写的,而您自己编写的代码则不会(例如,您必须声明必须保留在堆栈上的局部变量,需要较慢的查找时间,而不仅仅是一个临时寄存器变量)。因此,该语言本身执行的任何操作通常都会比您自己的代码更快。

I don't know any C# and yet I can put forward the likely answer.

Any programming language method are generally written in ways that take advantage of shortcuts made available by the processor that they run on - which your own written code will not (eg you'll have to declare local variables which will have to be kept on the stack, requiring slower lookup times, instead of just being a temporary register variable). Thus anything the language does natively will generally be quicker than your own code.

℉服软 2024-12-16 09:05:22

使用 ILSpy 并查看 LastIndexOf/IndexOf 方法的内部结构。这就是为什么它们更快的答案。

我有一种预感,List 内部使用 B 树或其他树,它具有 log(n) 的查找。您使用 for/foreach 所做的是执行线性查找,但需要一些额外的开销。如果您还记得数学课,那么您就会知道 log(n) 比线性线更平坦,因此查找速度更快......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文