473,508 Members | 2,337 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Static vs Non-Static Function Performance

We're currently doing some tests to determine the performance of static vs
non-static functions, and we're coming up with some odd(in our opinion)
results. We used a very simple setup. One class had a static function, and
the one class had a non-static function. Both of these functions did the
exact same thing.

The test function:
public void Test(){
decimal y = 2;
decimal x = 3;
decimal d = 0;

for(decimal z = 0; z < 1000000;z++){
if(z % 2 == 0){
d = y*d;
} else {
d = x*d;
}
}
}

The test running code:
for (int i = 0; i < 1000; i++) {
StaticTest.Test();
}

for (int i = 0; i < 1000; i++) {
NonStaticTest nst = new NonStaticTest();
nst.Test();
}

To our suprise the non-static approach ran in 15 minutes, and the static
approach ran in 17 minutes. We had figured that due to the need to
instantiate a new object with each call for the non-static approach, that
this way would take longer. We also tried running the non-static approach
first, and the static approach second, the results were the same. We ran
these tests 3 times each to make sure that we got a nice average.

Did we somehow bias the test towards the non-static approach? How is it that
with an object instantion going on, the non-static approach is able to run
in 2 minutes less time. This is of course a substantially large margin, and
could have some definite performance implications for those building
performance oriented code.

Thanks,
Steve
Nov 15 '05 #1
22 11999
Hi Steve,

There could be some optimisations going on that are giving false results.

--
Michael Culley
"Steve - DND" <ng@digitalnothing.com> wrote in message news:#w**************@tk2msftngp13.phx.gbl...
We're currently doing some tests to determine the performance of static vs
non-static functions, and we're coming up with some odd(in our opinion)
results. We used a very simple setup. One class had a static function, and
the one class had a non-static function. Both of these functions did the
exact same thing.

The test function:
public void Test(){
decimal y = 2;
decimal x = 3;
decimal d = 0;

for(decimal z = 0; z < 1000000;z++){
if(z % 2 == 0){
d = y*d;
} else {
d = x*d;
}
}
}

The test running code:
for (int i = 0; i < 1000; i++) {
StaticTest.Test();
}

for (int i = 0; i < 1000; i++) {
NonStaticTest nst = new NonStaticTest();
nst.Test();
}

To our suprise the non-static approach ran in 15 minutes, and the static
approach ran in 17 minutes. We had figured that due to the need to
instantiate a new object with each call for the non-static approach, that
this way would take longer. We also tried running the non-static approach
first, and the static approach second, the results were the same. We ran
these tests 3 times each to make sure that we got a nice average.

Did we somehow bias the test towards the non-static approach? How is it that
with an object instantion going on, the non-static approach is able to run
in 2 minutes less time. This is of course a substantially large margin, and
could have some definite performance implications for those building
performance oriented code.

Thanks,
Steve

Nov 15 '05 #2
"Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:O%****************@TK2MSFTNGP10.phx.gbl...
Hi Steve,

There could be some optimisations going on that are giving false results.

--
Michael Culley


Any idea what these enhancements could be? They should be doing the same
thing, should they not?

Steve
Nov 15 '05 #3
"Steve - DND" <ng@digitalnothing.com> wrote in message news:#q**************@TK2MSFTNGP11.phx.gbl...
Any idea what these enhancements could be? They should be doing the same
thing, should they not?
I can see several posibilities. The compiler might work out that nothing is returned from the function so optimise out some of the
code in the function. It could treat the function as static because it doesn't use an module level variables and it might not even
bother creating the object at all. All of these are just guesses though.

--
Michael Culley
"Steve - DND" <ng@digitalnothing.com> wrote in message news:#q**************@TK2MSFTNGP11.phx.gbl... "Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:O%****************@TK2MSFTNGP10.phx.gbl...
Hi Steve,

There could be some optimisations going on that are giving false results.

--
Michael Culley


Any idea what these enhancements could be? They should be doing the same
thing, should they not?

Steve

Nov 15 '05 #4
Thats because static methods are using locks to be Thread-safe. The always
do internally a Monitor.Enter() and Monitor.exit() to ensure Thread-safety.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 15 '05 #5
"Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:un**************@TK2MSFTNGP09.phx.gbl...
"Steve - DND" <ng@digitalnothing.com> wrote in message news:#q**************@TK2MSFTNGP11.phx.gbl...
Any idea what these enhancements could be? They should be doing the same
thing, should they not?


I can see several posibilities. The compiler might work out that nothing

is returned from the function so optimise out some of the code in the function. It could treat the function as static because it doesn't use an module level variables and it might not even bother creating the object at all. All of these are just guesses though.


Looks like you were correct. There seemed to be some optimizations going on.
When I changed things up a bit, I got *very* different results(static
running in less than 50% of the time).

Thanks,
Steve
Nov 15 '05 #6
maybe object pooling ?

--
Telmo Sampaio
MCSE (4 and 2k), MCSA, MCSD (6 and .NET), MCDBA, MCT, SPS, STA, SCSE, SAT,
MSF Practitioner, ITIL Certified
te***********@hotmail.com
"Steve - DND" <ng@digitalnothing.com> wrote in message
news:#q**************@TK2MSFTNGP11.phx.gbl...
"Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:O%****************@TK2MSFTNGP10.phx.gbl...
Hi Steve,

There could be some optimisations going on that are giving false results.
--
Michael Culley


Any idea what these enhancements could be? They should be doing the same
thing, should they not?

Steve

Nov 15 '05 #7
codymanix wrote:
Thats because static methods are using locks to be Thread-safe. The always
do internally a Monitor.Enter() and Monitor.exit() to ensure Thread-safety.


Are you sure? Do you have a pointer to some docs that describe this?

I find it hard to believe that it would do this automatically, since
it's easy enough to place the entire method body in a lock statement
block, and there are many cases where static methods would have no need
to use Monitors to ensure thread safety.

--
mikeb

Nov 15 '05 #8
He is right. Take a look at the Il code or google for it.

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"mikeb" <ma************@mailnull.com> wrote in message
news:u7**************@TK2MSFTNGP09.phx.gbl...
codymanix wrote:
Thats because static methods are using locks to be Thread-safe. The always do internally a Monitor.Enter() and Monitor.exit() to ensure Thread-safety.


Are you sure? Do you have a pointer to some docs that describe this?

I find it hard to believe that it would do this automatically, since
it's easy enough to place the entire method body in a lock statement
block, and there are many cases where static methods would have no need
to use Monitors to ensure thread safety.

--
mikeb

Nov 15 '05 #9
"Alvin Bruney" <vapordan_spam_me_not@hotmail_no_spamhotmail.com > wrote in message news:OM**************@tk2msftngp13.phx.gbl...
He is right. Take a look at the Il code or google for it.

So static functions should be avoided where optimum speed is needed?

--
Michael Culley

Nov 15 '05 #10
> > Are you sure? Do you have a pointer to some docs that describe this?

I find it hard to believe that it would do this automatically, since
it's easy enough to place the entire method body in a lock statement
block, and there are many cases where static methods would have no need
to use Monitors to ensure thread safety.

"Alvin Bruney" <vapordan_spam_me_not@hotmail_no_spamhotmail.com > wrote in
message news:OM**************@tk2msftngp13.phx.gbl... He is right. Take a look at the Il code or google for it.


I took a look at the IL code and disassembled code for both a static and
non-static function, and they're identical. Can you provide an example where
Monitor.Enter() or Monitor.Exit() is used automatically?

public class StaticTest {
public static void Test() {
decimal d = 2;
}
}

public class NonStaticTest {
public void Test() {
decimal d = 2;
}
}

***** Disassembly *****
..method public hidebysig instance void Test() cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init ([0] valuetype [mscorlib]System.Decimal d)
IL_0000: ldc.i4.2
IL_0001: newobj instance void [mscorlib]System.Decimal::.ctor(int32)
IL_0006: stloc.0
IL_0007: ret
} // end of method NonStaticTest::Test

..method public hidebysig static void Test() cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init ([0] valuetype [mscorlib]System.Decimal d)
IL_0000: ldc.i4.2
IL_0001: newobj instance void [mscorlib]System.Decimal::.ctor(int32)
IL_0006: stloc.0
IL_0007: ret
} // end of method StaticTest::Test

Steve
Nov 15 '05 #11
I think i am wrong on this one. The dissambly is painfully obvious that I
don't know what I am talking about :-)

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"Steve - DND" <steve!@!digitalnothing.com> wrote in message
news:Od**************@TK2MSFTNGP12.phx.gbl...
Are you sure? Do you have a pointer to some docs that describe this?

I find it hard to believe that it would do this automatically, since
it's easy enough to place the entire method body in a lock statement
block, and there are many cases where static methods would have no need to use Monitors to ensure thread safety.

"Alvin Bruney" <vapordan_spam_me_not@hotmail_no_spamhotmail.com > wrote in
message news:OM**************@tk2msftngp13.phx.gbl...
He is right. Take a look at the Il code or google for it.


I took a look at the IL code and disassembled code for both a static and
non-static function, and they're identical. Can you provide an example

where Monitor.Enter() or Monitor.Exit() is used automatically?

public class StaticTest {
public static void Test() {
decimal d = 2;
}
}

public class NonStaticTest {
public void Test() {
decimal d = 2;
}
}

***** Disassembly *****
.method public hidebysig instance void Test() cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init ([0] valuetype [mscorlib]System.Decimal d)
IL_0000: ldc.i4.2
IL_0001: newobj instance void [mscorlib]System.Decimal::.ctor(int32) IL_0006: stloc.0
IL_0007: ret
} // end of method NonStaticTest::Test

.method public hidebysig static void Test() cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init ([0] valuetype [mscorlib]System.Decimal d)
IL_0000: ldc.i4.2
IL_0001: newobj instance void [mscorlib]System.Decimal::.ctor(int32) IL_0006: stloc.0
IL_0007: ret
} // end of method StaticTest::Test

Steve

Nov 15 '05 #12
"Alvin Bruney" <vapordan_spam_me_not@hotmail_no_spamhotmail.com > wrote in message news:<OM**************@tk2msftngp13.phx.gbl>...
He is right. Take a look at the Il code or google for it.

Like Steve at DND, I did try this, and found no evidence of a simple
static method being automatically locked.


-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"mikeb" <ma************@mailnull.com> wrote in message
news:u7**************@TK2MSFTNGP09.phx.gbl...
codymanix wrote:
Thats because static methods are using locks to be Thread-safe. The always do internally a Monitor.Enter() and Monitor.exit() to ensure Thread-safety.


Are you sure? Do you have a pointer to some docs that describe this?

I find it hard to believe that it would do this automatically, since
it's easy enough to place the entire method body in a lock statement
block, and there are many cases where static methods would have no need
to use Monitors to ensure thread safety.

--
mikeb


--
mikeb
Nov 15 '05 #13
codymanix <do*********************@gmx.de> wrote:
Thats because static methods are using locks to be Thread-safe. The always
do internally a Monitor.Enter() and Monitor.exit() to ensure Thread-safety.


They definitely, definitely don't.

Here's an example program which shows two threads being in the same
method at the same time:

using System;
using System.Threading;

public class Test
{
static void Main()
{
Thread t1 = new Thread (new ThreadStart(Count));
Thread t2 = new Thread (new ThreadStart(Count));

t1.Name = "First thread";
t2.Name = "Second thread";

t1.Start();
t2.Start();
}

static void Count()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("{0} {1}", i,
Thread.CurrentThread.Name);
Thread.Sleep (500);
}
}
}

If you put a lock in yourself, eg lock (typeof(Test)) round the body of
Count, you get radically different results (i.e. one thread does the
whole count, then the second one does).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #14
Does anyone know where this urban myth about static methods got started?
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
codymanix <do*********************@gmx.de> wrote:
Thats because static methods are using locks to be Thread-safe. The always do internally a Monitor.Enter() and Monitor.exit() to ensure
Thread-safety.
They definitely, definitely don't.

Here's an example program which shows two threads being in the same
method at the same time:

using System;
using System.Threading;

public class Test
{
static void Main()
{
Thread t1 = new Thread (new ThreadStart(Count));
Thread t2 = new Thread (new ThreadStart(Count));

t1.Name = "First thread";
t2.Name = "Second thread";

t1.Start();
t2.Start();
}

static void Count()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("{0} {1}", i,
Thread.CurrentThread.Name);
Thread.Sleep (500);
}
}
}

If you put a lock in yourself, eg lock (typeof(Test)) round the body of
Count, you get radically different results (i.e. one thread does the
whole count, then the second one does).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #15
I don't know but it is out there. he he

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"Stu Smith" <st*****@remove.digita.com> wrote in message
news:u3**************@TK2MSFTNGP09.phx.gbl...
Does anyone know where this urban myth about static methods got started?
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
codymanix <do*********************@gmx.de> wrote:
Thats because static methods are using locks to be Thread-safe. The always do internally a Monitor.Enter() and Monitor.exit() to ensure

Thread-safety.

They definitely, definitely don't.

Here's an example program which shows two threads being in the same
method at the same time:

using System;
using System.Threading;

public class Test
{
static void Main()
{
Thread t1 = new Thread (new ThreadStart(Count));
Thread t2 = new Thread (new ThreadStart(Count));

t1.Name = "First thread";
t2.Name = "Second thread";

t1.Start();
t2.Start();
}

static void Count()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("{0} {1}", i,
Thread.CurrentThread.Name);
Thread.Sleep (500);
}
}
}

If you put a lock in yourself, eg lock (typeof(Test)) round the body of
Count, you get radically different results (i.e. one thread does the
whole count, then the second one does).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Nov 15 '05 #16
> I took a look at the IL code and disassembled code for both a static and
non-static function, and they're identical. Can you provide an example where Monitor.Enter() or Monitor.Exit() is used automatically?


It is done internally, there is no need that the il explicitly states it.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 15 '05 #17
codymanix <do*********************@gmx.de> wrote:
I took a look at the IL code and disassembled code for both a static and
non-static function, and they're identical. Can you provide an example

where
Monitor.Enter() or Monitor.Exit() is used automatically?


It is done internally, there is no need that the il explicitly states it.


No, it's *not* done internally, as my other post showed. The only
locking which goes on at all is to make sure that the type has been
initialised.

Do you have any evidence at all for your claim?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #18
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message news:MP************************@msnews.microsoft.c om...
Do you have any evidence at all for your claim?


This could be a myth that has been started because static methods are generally thread safe. It's kinda logical for someone to
conclude that some call is automatically made to make the method thread safe, when in fact it is thread safe (AFAIK, my knowledge of
threads is limited) because it does not use module level variables.

--
Michael Culley
Nov 15 '05 #19
"Stu Smith" <st*****@remove.digita.com> wrote in message
news:u3**************@TK2MSFTNGP09.phx.gbl...
Does anyone know where this urban myth about static methods got started?


I think it stems from the help files:

"Any public static (Shared in Visual Basic) members of this type are safe
for multithreaded operations. Any instance members are not guaranteed to be
thread safe."

I think people read that as "whats that skip.... the static memebers are
thread safe, they must be using some sort of locking mechanism...wicked i'll
pass that along"

andrew
Nov 15 '05 #20
100
Hi andrew,
Try to see what most of the static members do:
1. Static properties are readonly
2. Static methods doesn't use any other static variables and almost never
modified their arguments (some of them do like Array.Copy).

In this case you don't have to do any locking to ensure the thread safety.
Anyway if they need to do locking they will, but this is realy unlikely.
B\rgds
100

"andrew lowe" <andrew dot lowe at geac dot com> wrote in message
news:OC**************@tk2msftngp13.phx.gbl...
"Stu Smith" <st*****@remove.digita.com> wrote in message
news:u3**************@TK2MSFTNGP09.phx.gbl...
Does anyone know where this urban myth about static methods got started?
I think it stems from the help files:

"Any public static (Shared in Visual Basic) members of this type are safe
for multithreaded operations. Any instance members are not guaranteed to

be thread safe."

I think people read that as "whats that skip.... the static memebers are
thread safe, they must be using some sort of locking mechanism...wicked i'll pass that along"

andrew

Nov 15 '05 #21
"100" <10*@100.com> wrote in message
news:Oi**************@TK2MSFTNGP10.phx.gbl...
Hi andrew,
Try to see what most of the static members do:
1. Static properties are readonly
2. Static methods doesn't use any other static variables and almost never
modified their arguments (some of them do like Array.Copy).

In this case you don't have to do any locking to ensure the thread safety.
Anyway if they need to do locking they will, but this is realy unlikely.


Yes i know :) i was trying to illustrate how the myth was being perpetuated

andrew
Nov 15 '05 #22
that sounds so familliar. i think that is how i picked it up as well.

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"andrew lowe" <andrew dot lowe at geac dot com> wrote in message
news:OC**************@tk2msftngp13.phx.gbl...
"Stu Smith" <st*****@remove.digita.com> wrote in message
news:u3**************@TK2MSFTNGP09.phx.gbl...
Does anyone know where this urban myth about static methods got started?
I think it stems from the help files:

"Any public static (Shared in Visual Basic) members of this type are safe
for multithreaded operations. Any instance members are not guaranteed to

be thread safe."

I think people read that as "whats that skip.... the static memebers are
thread safe, they must be using some sort of locking mechanism...wicked i'll pass that along"

andrew

Nov 15 '05 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
4398
by: lothar | last post by:
re: 4.2.1 Regular Expression Syntax http://docs.python.org/lib/re-syntax.html *?, +?, ?? Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few...
3
12189
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in...
25
7543
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
4468
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
4
3035
by: Dave | last post by:
I need to add the ability to drag from a Windows Form and drop into a non dotNet application. For example, having a generated image in my app that I wish to drag out into explorer as a friendly way...
8
2453
by: John Hazen | last post by:
I want to match one or two instances of a pattern in a string. According to the docs for the 're' module ( http://python.org/doc/current/lib/re-syntax.html ) the '?' qualifier is greedy by...
5
2155
by: Joe | last post by:
I have an application which runs in a non-secure environment. I also have an application that runs in a secure environment (both on the same machine). Is there any way to share the session data for...
0
2321
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome...
399
12635
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or...
12
29791
by: puzzlecracker | last post by:
is it even possible or/and there is a better alternative to accept input in a nonblocking manner?
0
7225
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7123
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7046
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
5053
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4707
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3182
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1557
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
766
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
418
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.