Odd Function

J

Jonathan Rea

I did the following little test and was surprised by the results, why is the
"Initial : " time so slow ??? surely it should be faster than either of the
other two calls as it lacks a function call. I really dont get this...

i get the following output ....
Initial : 00:00:05.2031250
NonRef : 00:00:03.4062500
Ref : 00:00:04.1562500
Initial : 00:00:05.1406250
NonRef : 00:00:03.1875000
Ref : 00:00:03.9843750

Many thanks
Jon Rea

private void main()
{
int[] bob = new int[100000];
int repCount = 10000;
// initialise the bob array
for( int i = 0; i < length; i++ )
{
bob = 2;
}
DateTime T1;
DateTime T2;
TimeSpan TS1;
// now loop many times trying different calls
while(true)
{

T1 = DateTime.Now; // record the time
for( int j = 0; j < repCount; j++ )
{
for( int i = 0; i < bob.Length; i++ )
{
bob = 2;
}
}
T2 = DateTime.Now;
TS1 = T2 - T1;
Debug.WriteLine( "Initial : " + TS1.ToString() ); // for some reason this is
much slower than the two below ...


T1 = DateTime.Now;
for( int j = 0; j < repCount; j++ )
{
play( bob );
}
T2 = DateTime.Now;
TS1 = T2 - T1;
Debug.WriteLine( "NonRef : " + TS1.ToString() ); // why is this the fastes
method, surely the above is just an inline version of this ???


T1 = DateTime.Now;
for( int j = 0; j < repCount; j++ )
{
play( ref bob );
}
T2 = DateTime.Now;
TS1 = T2 - T1;
Debug.WriteLine( "Ref : " + TS1.ToString() );
}
}

// the following two function calls for interaction with the bob array, bob
is passed in one by ref in one and normally in the other

private void play( int[] b )
{
for( int i = 0; i < b.Length; i++ )
{
b = 2;
}


}
private void play( ref int[] b )
{
for( int i = 0; i < b.Length; i++ )
{
b = 2;
}
}
 
V

Vijaye Raji

This is definitely something to do with the optimization performed at the
JIT level. The reason why the first one may not perform as well in your
case is that the JIT'ter is able to optimize small methods better than a few
lines of code in a large method. It's hard for the JIT'ter to identify
optimizable portions of code in a big method (I think).

Try breaking these three out into their own separate smaller functions.
They perform as expected.

-vJ
 

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