1

假设我有一个 C# 接口,IMyInterface定义如下:

// C# code
public interface IMyInterface
{
  string MyProperty { get; }
}

假设我还有一个 C++/CLI 类,MyConcreteClass它实现了这个接口,并且它的头声明如下:

public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual property String^ MyProperty 
  {
    String^ get() sealed { return String::Empty; };
    void set( String^ s ) sealed { };
  }
};

显然,当您通过接口访问虚拟成员时,运行时必须在类中查找实现,并且会比成员不是虚拟的要慢。

IMyInterface obj;
obj->MyProperty = "HELLO";

我专门询问直接在具体对象类型上使用虚拟成员的性能。MyProperty如果是虚拟成员,这会更慢吗?

MyConcreteClass obj;
obj->MyProperty = "HELLO";
4

1 回答 1

4

Virtual methods are slower because the runtime has to check for an actual implementation of the method. So it is 1 additional check. You can still hundreds of thousands of these per second. So don't stress about it. In Java every method is virtual by default.

UPDATE: I am not sure about how introducing c++ changes things. My guess is that is would be similar because you are still accessing a virtual method. I am not sure how it would change it. But once again this is just my guess. Hopefully someone else can help out more.

于 2013-03-26T09:18:29.077 回答