Static methods slower?

  • Thread starter =?iso-8859-1?B?QW5kcuk=?=
  • Start date
?

=?iso-8859-1?B?QW5kcuk=?=

Hello,

I'm having a discussion with my colleagues (and boss) over the use of
static methods in a class.

My colleagues say that static methods should be avoided whenever is
possible, because their use slows down the application.

For me, this sounds absurd - I believe that static methods should be
used whenever they're necessary. However, I wasn't able to find any
reliable documents on that. Does anyone knows of a reliable source
(like Microsoft) that discusses that?

Thank you in advance,

André
 
A

Andy

That's just a silly argument. Not all methods make sense at a instance
level.

Instead of trying to prove them wrong, ask them to prove that static
methods are in fact slower. If anything, I would think they are
faster, because they are not overridable and don't have to look in a
virtual table, IIRC.

Also, ask they why they are concerned about performance of a method
call, when .Net has garbage collection, boxing / unboxing, etc.

If you're programming in .Net, you should have already decided you're
not going to worry about nanoseconds of performance. If you are, you
should be writing your code in C or assembly..

Andy
 
?

=?iso-8859-1?B?QW5kcuk=?=

That's just a silly argument. Not all methods make sense at a instance
level.

Instead of trying to prove them wrong, ask them to prove that static
methods are in fact slower. If anything, I would think they are
faster, because they are not overridable and don't have to look in a
virtual table, IIRC.

Also, ask they why they are concerned about performance of a method
call, when .Net has garbage collection, boxing / unboxing, etc.

If you're programming in .Net, you should have already decided you're
not going to worry about nanoseconds of performance. If you are, you
should be writing your code in C or assembly..

Hello, Andy,

I positively agree with you. But, unfortunately, unless I provide some
reliable documentation (like Microsoft's) on that, I can't have my
point made... :-(

André
 
D

Dustin Campbell

I'm having a discussion with my colleagues (and boss) over the use of
static methods in a class.

My colleagues say that static methods should be avoided whenever is
possible, because their use slows down the application.

For me, this sounds absurd - I believe that static methods should be
used whenever they're necessary. However, I wasn't able to find any
reliable documents on that. Does anyone knows of a reliable source
(like Microsoft) that discusses that?

You're right. That's absurd. Instance methods have more overhead than static
methods.

Here's a very simple console application (build with .NET Framework 2.0)
that will demonstrate the difference:

using System;
using System.Diagnostics;

namespace StaticMethodSpeedTest
{
class Program
{
static double Average(long[] values)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
sum += values;

return sum / values.Length;
}

class TestClass
{
public void InstanceMethod()
{
}
public static void StaticMethod()
{
}
}

static void Main(string[] args)
{
const int NUM_SAMPLES = 1000;
const int NUM_CALLS = 1000000;

long[] samples = new long[NUM_SAMPLES];
Stopwatch watch = new Stopwatch();

for (int i = 0; i < NUM_SAMPLES; i++)
{
watch.Reset();
watch.Start();

for (int j = 0; j < NUM_CALLS; j++)
TestClass.StaticMethod();

watch.Stop();

samples = watch.ElapsedMilliseconds;
}

Console.WriteLine("{0:###,###,###,##0} static method calls took approximately
{1:0.######} seconds", NUM_CALLS, Average(samples) / 1000);

TestClass c = new TestClass();
for (int i = 0; i < NUM_SAMPLES; i++)
{
watch.Reset();
watch.Start();

for (int j = 0; j < NUM_CALLS; j++)
c.InstanceMethod();

watch.Stop();

samples = watch.ElapsedMilliseconds;
}

Console.WriteLine("{0:###,###,###,##0} instance method calls took approximately
{1:0.######} seconds", NUM_CALLS, Average(samples) / 1000);
}
}
}

I get the following results:

1,000,000 static method calls: 0.006008
1,000,000 instance method calls: 0.006152

As you can see, the difference is extremely small but the edge goes to static
methods.




Best Regards,
Dustin Campbell
Developer Express Inc
 
A

Andy

Oh, and again, I would really push them against the wall and demand
them to back up their point with some documentation.
 
B

Brian Gideon

André,

If I had to make a guess I'd say static methods are generally faster
for the same reasons Andy stated.

Regardless, is the marginal performance difference really worth
sacrificing correctness and readability?

Brian
 
D

Dustin Campbell

I positively agree with you. But, unfortunately, unless I provide
I suggestion you move on then, no sense in working with people that
have such absurd beliefs.

Here's one link I found that actually claims statics are faster, from
an MVP..

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1047372&SiteID=1

That MVP is correct. The majority of savings is because the 'this' pointer
does not need to be loaded onto the stack before calling a static method.
I would love to know where these co-workers came up with such a ridiculous
notion.

Best Regards,
Dustin Campbell
Developer Express Inc.
 
?

=?iso-8859-1?B?QW5kcuk=?=

That MVP is correct. The majority of savings is because the 'this' pointer
does not need to be loaded onto the stack before calling a static method.
I would love to know where these co-workers came up with such a ridiculous
notion.

According to their point, a class with static methods will load in the
initialization of the program, while a class without static methods
would only be loaded when the class is used. This, in a program with
many classes, would slow down the initialization.

Does it make sense?

André
 
S

Steve Drake

It sounds like you know what you're doing and your boss does not :D.

good look

Dustin's Example is spot on.

If you don't need to manage state etc, then static are norms good.

From my experiences, I have normally see the following :

Facade
100% instance
some times read only calls are static.

Rules
Real code goes in instances, some helper stuff goes in static methods.

Data Layer
100% static and 100% no state.

The facade is debatable, we use AOP to-do achieve transactions in our facade
so it works best as instance, see
http://stevesdotnetblog.spaces.live.com/blog/cns!DB522AEA514170CA!109.entry
For some examples on this.

There are good arguments, but performance is not one of them.

But, if you have to create an instance of the class each time just to call a
simple static method then it's really going to suffer. I changed Dustin's
example

I got the following numbers:

10,000,000 static method calls took approximately 0.002045 seconds
10,000,000 instance method calls took approximately 0.002036 seconds
10,000,000 instance method re-creating class took approximately 0.130855
seconds

Note, I used 10,000,000 calls rather than 1,000,000 as I ran a release
build.

Good luck.

Steve






Hello,

I'm having a discussion with my colleagues (and boss) over the use of
static methods in a class.

My colleagues say that static methods should be avoided whenever is
possible, because their use slows down the application.

For me, this sounds absurd - I believe that static methods should be
used whenever they're necessary. However, I wasn't able to find any
reliable documents on that. Does anyone knows of a reliable source
(like Microsoft) that discusses that?

Thank you in advance,

André
 
D

Dustin Campbell

That MVP is correct. The majority of savings is because the 'this'
According to their point, a class with static methods will load in the
initialization of the program, while a class without static methods
would only be loaded when the class is used. This, in a program with
many classes, would slow down the initialization.

Does it make sense?

They are wrong about that as well. Classes with static methods are not loaded
when a program is initialized. They are loaded the first time that a class
is used. Consider this example:

using System;

namespace StaticMethodTest
{
class ClassWithStaticMethods
{
static int g_Data;

static ClassWithStaticMethods()
{
Console.WriteLine("ClassWithStaticMethods loaded");

g_Data = 42;
}

public static int GetData()
{
return g_Data;
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main() entered");

Console.WriteLine("About to access ClassWithStaticMethods");
Console.WriteLine("ClassWithStaticMethods.Data = {0}", ClassWithStaticMethods.GetData());

Console.WriteLine("Main() exiting");
}
}
}

It outputs the following text to the console:

Main() entered
About to access ClassWithStaticMethods
ClassWithStaticMethods loaded
ClassWithStaticMethods.Data = 42
Main() exiting

Obviously, ClassWithStaticMethods was not loaded until the first time that
it was accessed by the application.

Best Regards,
Dustin Campbell
Developer Express Inc
 
W

Willy Denoyette [MVP]

André said:
That MVP is correct. The majority of savings is because the 'this' pointer
does not need to be loaded onto the stack before calling a static method.
I would love to know where these co-workers came up with such a ridiculous
notion.

According to their point, a class with static methods will load in the
initialization of the program, while a class without static methods
would only be loaded when the class is used. This, in a program with
many classes, would slow down the initialization.

Does it make sense?

No it doesn't, the class will be loaded at first call of a static method, NOT at program
initialization time.

Willy.
 
B

Barry Kelly

André said:
According to their point, a class with static methods will load in the
initialization of the program, while a class without static methods
would only be loaded when the class is used. This, in a program with
many classes, would slow down the initialization.

Does it make sense?

No :) Types are initialized at a runtime-determined time, which is
usually just as the first member (static or constructor in the case of
instance) is accessed.

To be sure, write a test with class constructors etc.

-- Barry
 
W

Willy Denoyette [MVP]

Dustin Campbell said:
That MVP is correct. The majority of savings is because the 'this' pointer does not need
to be loaded onto the stack before calling a static method. I would love to know where
these co-workers came up with such a ridiculous notion.

Actually the this pointer is not passed on the stack, managed code used the CLR calling
convention when calling instance methods, here the this pointer and the first argument (if
any) are passed in a register.

Willy.
 
D

Dustin Campbell

Dustin Campbell said:
message
Actually the this pointer is not passed on the stack, managed code
used the CLR calling convention when calling instance methods, here
the this pointer and the first argument (if any) are passed in a
register.

Right. Thanks for the clarification Willy.

OK, so it's even *less* of a difference. :)

Best Regards,
Dustin Campbell
Developer Express Inc
 
J

Jon Skeet [C# MVP]

André said:
I positively agree with you. But, unfortunately, unless I provide some
reliable documentation (like Microsoft's) on that, I can't have my
point made... :-(

Your point should be that whoever wants to bend the design out of shape
for the sake of performance ought to prove that:

a) the performance needs improvement
b) making the change makes such a significant improvement that it's
worth the reduction in readability/elegance etc

If you were suggesting turning "natural" instance methods into static
methods for the sake of performance, that would be one thing, but if
they're suggesting turning "natural" static methods into instance
methods, the onus should be on them to make the case (with evidence).
 
D

Dustin Campbell

To be sure, write a test with class constructors etc.
Good point - I had forgotten about this.

Same. Thanks Jon.

Best Regards,
Dustin Campbell
Developer Express Inc.
 
M

Marc Gravell

First: I agree with the other posters: no (intrinsic) overhead on
static; quite the opposite (although trivial).
There is, however, one valid argument (that I can think of) for this
view, but it is not the common case:

Static methods should (as a general rule) be thread-safe. In the vast
majority of cases this is a non-issue, since the method is a utility
method that only acts on it's arguments so is inherently thread-safe
without any coding changes or special behaviours.

If, however, the static method talks to static fields etc, then you
start having to add locks; in most usage the lock will be uncontested,
so this will /still/ be blindingly fast (since CLR locks work very
efficiently inside the runtime, unlike OS locks such as Mutex etc
which have a much higher overhead). And equally, this is no different
to if this was implemented as an instance method, where the same
instance was shared between threads (for whatever reason). In a high
volume scenario, however, it is possible (with a bad design) that a
long-running, synchronised*, static method could become a bottleneck.
Again: I stress "bad design"; in this case it is not the "static"s
fault, rather that of the (specific) system's architects.

(*: by which I mean locked (Monitor), or worse: Mutex'd / Semaphore'd
by the OS)

But I stress: this is /not/ the norm; in my experience most static
methods are (relatively) simple utility methods that have no such
overhead.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top