C# 将方法/属性标记为虚拟的性能影响是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/530799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:00:18  来源:igfitidea点击:

What are the performance implications of marking methods / properties as virtual?

c#performancevirtual

提问by Erik Forbes

Question is as stated in the title: What are the performance implications of marking methods / properties as virtual?

问题如标题所述:将方法/属性标记为虚拟的性能影响是什么?

Note - I'm assuming the virtual methods will notbe overloaded in the common case; I'll usually be working with the base class here.

注意 - 我假设虚拟方法在常见情况下不会被重载;我通常会在这里使用基类。

采纳答案by dsimcha

Virtual functions only have a very small performance overhead compared to direct calls. At a low level, you're basically looking at an array lookup to get a function pointer, and then a call via a function pointer. Modern CPUs can even predict indirect function calls reasonably well in their branch predictors, so they generally won't hurt modern CPU pipelines too badly. At the assembly level, a virtual function call translates to something like the following, where Iis an arbitrary immediate value.

与直接调用相比,虚拟函数只有非常小的性能开销。在低级别上,您基本上是在查看数组查找以获取函数指针,然后通过函数指针进行调用。现代 CPU 甚至可以在其分支预测器中相当好地预测间接函数调用,因此它们通常不会严重损害现代 CPU 管道。在程序集级别,虚函数调用转换为如下所示的内容,其中I是任意立即数。

MOV EAX, [EBP + I] ; Move pointer to class instance into register
MOV EBX, [EAX] ;  Move vtbl pointer into register.
CALL [EBX + I]  ;   Call function

Vs. the following for a direct function call:

对比 以下是直接函数调用:

CALL I  ;  Call function directly

The real overhead comes in that virtual functions can't be inlined, for the most part. (They can be in JIT languages if the VM realizes they're always going to the same address anyhow.) Besides the speedup you get from inlining itself, inlining enables several other optimizations such as constant folding, because the caller can know how the callee works internally. For functions that are large enough not to be inlined anyhow, the performance hit will likely be negligible. For very small functions that might be inlined, that's when you need to be careful about virtual functions.

真正的开销在于虚函数在大多数情况下不能内联。(它们可以使用 JIT 语言,如果 VM 意识到无论如何它们总是会到达相同的地址。)除了您从内联本身获得的加速之外,内联还启用了其他一些优化,例如常量折叠,因为调用者可以知道被调用者如何在内部工作。对于足够大而不能内联的函数,性能影响可能可以忽略不计。对于可能被内联的非常小的函数,那是您需要小心虚函数的时候。

Edit: Another thing to keep in mind is that all programs require flow control, and this is never free. What would replace your virtual function? A switch statement? A series of if statements? These are still branches that may be unpredictable. Furthermore, given an N-way branch, a series of if statements will find the proper path in O(N), while a virtual function will find it in O(1). The switch statement may be O(N) or O(1) depending on whether it is optimized to a jump table.

编辑:要记住的另一件事是所有程序都需要流量控制,而这从来都不是免费的。什么会取代你的虚函数?switch 语句?一系列 if 语句?这些仍然是可能无法预测的分支。此外,给定一个 N 路分支,一系列 if 语句将在 O(N) 中找到正确的路径,而虚函数将在 O(1) 中找到它。switch 语句可能是 O(N) 或 O(1),这取决于它是否针对跳转表进行了优化。

回答by Richard A

From your tags, you're talking c#. I can only answer from a Delphi perspective. I think it will be similar. (I am expecting negative feedback here :) )

从你的标签来看,你说的是 c#。我只能从德尔福的角度来回答。我认为这将是相似的。(我在这里期待负面反馈:))

A static method will be linked at compile time. A virtual method requires a lookup at run-time to decide which method to call, so there is a small overhead. It is only significant if the method is small and called often.

静态方法将在编译时链接。虚拟方法需要在运行时查找来决定调用哪个方法,因此开销很小。只有当方法很小并且经常调用时才有意义。

回答by Pop Catalin

On the desktop side it doesn't matter if the method are overloaded or not, they incur a extra level of indirection through the method pointer table (Virtual method table), which means roughly 2 extra memory reads through indirection before the method call compared a non virtual methods on non sealed classes and non final methods.

在桌面端,方法是否重载无关紧要,它们会通过方法指针表(虚拟方法表)产生额外的间接级别,这意味着在方法调用之前通过间接读取大约 2 个额外的内存非密封类和非最终方法上的非虚拟方法。

[As an interesting fact, on compact framework version 1.0 the overheat is greater as it doesn't use virtual method tables but simply reflection to discover the right method to execute when calling a virtual method.]

[作为一个有趣的事实,在紧凑型框架 1.0 版上过热更大,因为它不使用虚方法表,而只是在调用虚方法时通过反射来发现正确的方法来执行。]

Also virtual methods are far less likely to be candidates for inlining or other optimizations like tail call than non virtual methods.

此外,与非虚拟方法相比,虚拟方法不太可能成为内联或其他优化(如尾调用)的候选者。

Roughly this is the performance hierarchy of method calls:

大致这是方法调用的性能层次结构:

Non virtual methods < Virtual Metods < Interface methods (on classes) < Delegate dispatch < MethodInfo.Invoke < Type.InvokeMember

非虚拟方法 < 虚拟方法 < 接口方法(在类上)< 委托调度 < MethodInfo.Invoke < Type.InvokeMember

But none of these performance implications of various dispatch mechanisms don't matter unless you proven it by measuring;) (And even then the architecture implications, readability etc might have a big weight on which one to chose)

但是,各种调度机制的这些性能影响都无关紧要,除非您通过测量来证明它;)(即使如此,架构影响、可读性等可能对选择哪个有很大的影响)

回答by abelenky

Typically a virtual method simply goes through one table-of-function-pointers to reach the actual method. This means one extra dereference and one more round-trip to memory.

通常,虚拟方法只是通过一个函数指针表来访问实际方法。这意味着一次额外的取消引用和一次更多的内存往返。

While the cost is not absolutely ZERO, it is extremely minimal. If it helps your program at all to have virtual functions, by all means, do it.

虽然成本不是绝对零,但它非常小。如果它有助于你的程序拥有虚函数,一定要这样做。

Its far better to have a well-designed program with a tiny, tiny, tiny performance hit rather than a clumsy program just for the sake of avoiding the v-table.

拥有一个精心设计的程序,其性能受到很小的影响,而不是仅仅为了避免 v-table 的笨拙程序。

回答by jalf

It's hard to say for sure, because the .NET JIT compiler may be able to optimize the overhead away in some (many?) cases.

很难确定,因为 .NET JIT 编译器可能能够在某些(许多?)情况下优化开销。

But if it does not optimize it away, we are basically talking about an extra pointer indirection.

但是如果它不优化它,我们基本上是在谈论一个额外的指针间接。

That is, when you call a non-virtual method, you have to

也就是说,当你调用一个非虚方法时,你必须

  1. Save registers, generate the function prologue/epilogue to set up arguments, copy the return value and such.
  2. jump to a fixed, and statically known, address
  1. 保存寄存器,生成函数 prologue/epilogue 来设置参数,复制返回值等等。
  2. 跳转到一个固定的、静态已知的地址

1 is the same in both cases. As for 2, with a virtual method, you have to instead read from a fixed offset in the object's vtable, and then jump to wherever that points. That makes branch prediction harder, and it may push some data out of the CPU cache. So the difference isn't huge, but it can add up if you make every function call virtual.

1 在这两种情况下是相同的。至于 2,使用虚方法,您必须从对象的 vtable 中的固定偏移量读取,然后跳转到指向的任何位置。这使得分支预测更加困难,并且可能会将一些数据从 CPU 缓存中推出。所以差异不是很大,但是如果你使每个函数调用都是虚拟的,它就会加起来。

It can also inhibit optimizations. The compiler can easily inline a call to a nonvirtual function, because it knows exactly which function is called. With a virtual function, that is a bit trickier. The JIT-compiler may still be able to do it, once it's determined which function is called, but it's a lot more work.

它还可以抑制优化。编译器可以轻松地内联对非虚拟函数的调用,因为它确切地知道调用的是哪个函数。对于虚函数,这有点棘手。一旦确定调用哪个函数,JIT 编译器可能仍然能够执行此操作,但需要做更多的工作。

All in all, it can still add up, especially in performance-critical areas. But it's not something you need to worry about unless the function is called at the very least a few hundred thousand times per second.

总而言之,它仍然可以加起来,尤其是在性能关键领域。但这不是您需要担心的,除非该函数每秒至少被调用数十万次。

回答by Crashworks

I ran this test in C++. A virtual function call takes (on a 3ghz PowerPC) between 7-20 nanoseconds longer than a direct function call. That means it really only matters for functions you plan on calling a million times per second, or for functions that are so small that the overhead may be larger than the function itself. (For example, making accessor functions virtual out of blind habit is probably unwise.)

我用 C++ 运行了这个测试。虚拟函数调用(在 3ghz PowerPC 上)比直接函数调用长 7-20 纳秒。这意味着它实际上只对您计划每秒调用一百万次的函数有用,或者对于那些开销可能大于函数本身的小函数很重要。(例如,出于盲目的习惯而将访问器功能虚拟化可能是不明智的。)

I haven't run my test in C#, but I expect that the difference will be even less there, since nearly every operation in the CLR involves an indirect anyway.

我还没有在 C# 中运行我的测试,但我希望那里的差异会更小,因为 CLR 中的几乎每个操作都涉及间接的。

回答by Jon Limjap

Rico Mariani outlines issues regarding performance in his Performance Tidbits blog, where he stated:

Rico Mariani 在他的Performance Tidbits 博客中概述了有关性能的问题,他说:

Virtual Methods:Are you using virtual methods when direct calls would do? Many times people go with virtual methods to allow for future extensibility. Extensibility is a good thing but it does come at a price – make sure your full extensibility story is worked out and that your use of virtual functions is actually going to get you to where you need to be. For instance, sometimes people think through the call site issues but then don't consider how the “extended” objects are going to be created. Later they realize that (most of) the virtual functions didn't help at all and they needed an entirely different model to get the “extended” objects into the system.

Sealing:Sealing can be a way of limiting the polymorphism of your class to just those sites where polymorphism is needed. If you will fully control the type then sealing can be a great thing for performance as it enables direct calls and inlining.

虚拟方法:当直接调用可以使用时,您是否使用虚拟方法?很多时候人们使用虚拟方法来考虑未来的可扩展性。可扩展性是一件好事,但它确实是有代价的——确保你的完整可扩展性故事得到解决,并且你对虚函数的使用实际上会让你到达你需要的地方。例如,有时人们会仔细考虑调用站点问题,但不会考虑将如何创建“扩展”对象。后来他们意识到(大部分)虚函数根本没有帮助,他们需要一个完全不同的模型来将“扩展”对象引入系统。

密封:密封可以是一种将类的多态性限制在需要多态性的站点的方法。如果您将完全控制类型,那么密封对于性能来说可能是一件好事,因为它可以实现直接调用和内联。

Basically the argument against virtual methods is that it disallows the code to be a candidate of in-lining, as opposed to direct calls.

基本上反对虚拟方法的论点是它不允许代码成为内联的候选者,而不是直接调用。

In the MSDN article Improving .NET Application Performance and Scalability, this is further expounded:

在MSDN文章Improving .NET Application Performance and Scalability 中,进一步阐述了这一点:

Consider the Tradeoffs of Virtual Members

Use virtual members to provide extensibility. If you do not need to extend your class design, avoid virtual members because they are more expensive to call due to a virtual table lookup and they defeat certain run-time performance optimizations. For example, virtual members cannot be inlined by the compiler. Additionally, when you allow subtyping, you actually present a very complex contract to consumers and you inevitably end up with versioning problems when you attempt to upgrade your class in the future.

考虑虚拟成员的权衡

使用虚拟成员提供可扩展性。如果您不需要扩展您的类设计,请避免使用虚拟成员,因为由于虚拟表查找而调用它们的成本更高,并且它们会破坏某些运行时性能优化。例如,虚拟成员不能被编译器内联。此外,当您允许子类型时,您实际上向消费者呈现了一个非常复杂的契约,并且当您将来尝试升级您的类时,您不可避免地会遇到版本控制问题。

A criticism of the above, however, comes from the TDD/BDD camp (who wants methods defaulting to virtual) arguing that the performance impact is negligible anyway, especially as we get access to much faster machines.

然而,对上述内容的批评来自 TDD/BDD 阵营(他们希望方法默认为虚拟),认为无论如何性能影响都可以忽略不计,尤其是当我们可以访问速度更快的机器时。