开发者

Can making a method static improve performance, and under what circumstances?

When, if ever, is it faster to pass arguments as arguments to a static method rather than have the method be non-static and access the same values via instance members. Assume the method accesses these members in a read-only fashion.

All other things being equal, calling a static method is slightly faster than calling an instance method.

All other things being equal, calling a method with no arguments is slightly faster than calling one with arguments.

Consider:

private Thing _thing;

void DoTheThing()
{
    _thing.DoIt();
}

Versus this equivalent code:

private Thing _thing;

// caller's responsibility to pass "_thing"
static void DoTheThing(Thing thing)
{
    thing.DoIt();
}

I can't think of a real-world situation where this kind of optimisation would really add any value, but as a thought experiment (for those who like to discuss this kind of thing), is there really a benefit, and if so then how many arguments (of what types etc) tip the balance the other way?

Would any other factors play into the consideration of this? The static method accesses _thing as a local va开发者_运维问答riable rather than a field, for example.


There's one possible performance benefit I can thnk of (for a non-virtual method): the static method doesn't need to test a reference for nullity first (to throw a NullReferenceException where appropriate).

I don't think this currently gives any advantage, but it's a possible one. I'm not sure it would apply in your particular example, though - and it's hard to see how it would apply in any case where you actually wanted to use the value.


In your case (I'm assuming the code sample would be in the Thing class) static and non-static will have no speed difference at all. This is from YOUR link:

  • 0.2 0.2 inlined static call
  • 0.2 0.2 inlined this inst call

So there is no sense at all in making it static for a speed boost.

Also take into account that the values provided in your linked page are from .Net 1.1 and way outdated.


I am not sure about the performance statics among static methods and instance methods.

But I believe that the decision should be taken whether you make it as a static method or instance method on the basis of object design. If by calling your method, the state of the object is not altered, then you should make that method as static method (method for the type, not for a perticular instance of the type).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜