VB.NET 中的 foreach 比 C# 中的 foreach 快吗?
我的同事说,在之前的一次采访中,他了解到VB.Net中的foreach比c#的foreach更快。 他被告知这是因为两者都有不同的 CLR 实现。
从 C++ 的角度来看,我很好奇这是为什么,有人告诉我我需要先阅读 CLR。 谷歌搜索 foreach 和 CLR 并不能帮助我理解。
有人能很好地解释为什么 foreach 在 VB.Net 中比在 C# 中更快吗? 还是我的同事被误导了?
My co-worker said that in a previous interview, he learned that foreach is faster in VB.Net than c#'s foreach. He was told that this was because both have different CLR implementation.
Coming from a C++ perspective, I'm curious on why this is and I was told that I need to read up on CLR first. Googling foreach and CLR doesn't help me understand.
Does anyone have a good explanation on why foreach is faster in VB.Net than in c#? Or was my co-worker misinformed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C# 和 VB.Net 在 IL 级别上没有显着差异。 两个版本之间到处都抛出了一些额外的 Nop 指令,但没有任何实际改变正在发生的事情。
方法如下:(在 C# 中)
在 VB.Net 中:
这是 C# 版本的 IL:
这是 VB.Net 版本的 IL:
There is no significant difference at the IL level between C# and VB.Net. There are some additional Nop instructions thrown in here and there between the two versions, but nothing that actually changes what is going on.
Here is the method: (in C#)
And in VB.Net:
Here is the IL for the C# version:
Here is the IL for the VB.Net version:
我对这个说法有点怀疑。 foreach 构造对两种语言的工作方式相同,因为它获取 IEnumerator 来自托管对象并对其调用 MoveNext()。 原始代码是用 VB.NET 还是 C# 编写的并不重要,它们都编译成相同的东西。
在我的测试计时中,对于很长的迭代,VB.NET 和 C# 中的相同 foreach 循环的间隔永远不会超过 ~1%。
c#:
VB.NET:
I'm a little suspicious of this claim. The foreach construct works the same way against both languages, in that it gets the IEnumerator from the managed object and calls MoveNext() on it. Whether the original code was written in VB.NET or c# should not matter, they both compile to the same thing.
In my test timings, the same foreach loop in VB.NET and c# were never more than ~1% apart for very long iterations.
c#:
VB.NET:
对于循环字符串数组的简单 foreach,这是 VB 生成的 IL 代码:
这是 C# 生成的 IL 代码:
唯一的区别是 VB 使用
add.ovf
和conv .ovf.i4
而不是add
和conv.i4
。 这意味着 VB 代码会执行两次额外的溢出检查,并且可能会稍微慢一些。For a simple foreach looping a string array, this is the IL code produced by VB:
And this is the IL code produced by C#:
The only difference is that VB uses
add.ovf
andconv.ovf.i4
instead ofadd
andconv.i4
. That means that the VB code does two extra overflow checks, and might be slightly slower.VB.NET 和 C# 都使用相同的 CLR。 我只是使用以下代码做了一个快速的基准测试:
C# 版本:
VB.NET 版本:
在执行 500000 次迭代的发布版本(最重要)上,C# 代码稍微快一点,但也仅差一点点。
调试版本:
发布版本:
VB.NET and C# both use the same CLR. I just did a quick finger in the air benchmark using the following code:
C# version:
VB.NET version:
On the release build (which counts most) performing 500000 iterations the C# code is marginally faster but only by a whisker.
Debug Build:
Release Build:
你应该做一个实验。 抓住(很棒的).NET Reflector,用每种语言构建一个简单的测试用例,看看生成的MSIL是否相同。
You should do an experiment. Grab the (awesome) .NET Reflector, build a simple test case in each language, and see whether the generated MSIL is the same or not.