Performance testing static methods versus instance methods

I was creating several static methods at work today and I started to wonder about how static methods perform versus instance methods. So I created a quick test, that simply calls a static method 5,000,000 times and an instance method the same number of times. Both methods are identical, they simply return true, but as you can see from the results, the static method executes 20-50% slower than the instance method.

To test for yourself, simply click the "Test Instance Method" button to run the instance method test, and then when it’s done you can click the button again to start the static method test. Your results for each test are displayed in the DataGrid. All times are represented in milliseconds.

You can view the source of this application here.

Get Adobe Flash player

Tags: , , ,

3 Responses to “Performance testing static methods versus instance methods”

  1. Ian Appleby Says:

    Interesting, although I don’t think it’s the method call itself which takes the time.

    I tried moving both the test methods to the calling class. This changed the results significantly. The times are now almost identical. This suggests the time is taken finding the definition of the TestStaticMethod class each time, rather than running the method itself. That could still matter, but it’s a different outcome.

    What’s perhaps more interesting, is that the instance method got slower. Now I’m not exactly sure, but I suspect this is due to the additional work of finding the method on a larger class.

  2. Kalen Gibbons Says:

    Thanks for the feedback Ian, that’s really interesting. I assumed that the difference in time was in looking up the class definition, and that’s what I was really trying to verify with this experiment. At the time, I was writing a collection of utility classes that contained nothing but static methods, and I was curious about how this approach would effect performance versus an instance implementation.

    I didn’t try testing a static and instance method within the same class, so thanks for providing us with that information.

  3. Glenna Says:

    It’s hard to find your articles in google. I
    found it on 22 spot, you should build quality backlinks ,
    it will help you to rank to google top 10. I know how to help you, just type
    in google – k2 seo tricks

Leave a Reply