Showing posts with label Design. Show all posts
Showing posts with label Design. Show all posts

Monday, July 16, 2007

Benchmarking LINQ vs. DAAB vs. ADO.NET



Abstract: This article presents benchmarking results of performance of SP calls using LINQ, Data-access application block and ADO.NET.

Some time ago I was doing LINQ performance benchmarking, looking for an option of replacing our existing data layer with it. One thing that was especially important for me to check - was performance of executing SP's. The reason is that most of our DAL logic resides in SP's at one hand and that performance-critical parts are implemented as SP's as well (for all the good reasons, like possibility to benefit from queries compilation etc).

Below are performance benchmarking results of execution uspGetManagerEmployees SP from AdventureWorks DB. (Basically it does some sort of JOIN to retrieve records of employees data for the specified Manager ID).
I tested three data-access models - raw ADO.NET vs. DAAB (our current DAL workhorse) vs. LINQ (May 2006 preview version).

As a prerequisite for running this test you'll need AdventureWorks DB and installation of LINQ.
Few side-notes:
  • I've left opening of DB connection out of the context of benchmarked section. Only SP execution is measured.

  • I use ExecuteReader rather than ExecuteDataSet, as it is much more lightweight. For LINQ benchmark I using GetEnumerator().

So here goes the test code:

1. Plain ADO.NET:


public static void SqlSPBench()
{
string connectionString =
"Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True";

using( SqlConnection conn = new SqlConnection( connectionString ) )
{
conn.Open();

Stopwatch watch = new Stopwatch();
watch.Start();

int count = 10000;
for( int i = 0; i < count; i++ )
{
using( SqlCommand cmd = new SqlCommand() )
{
cmd.Connection = conn;
cmd.CommandText = "uspGetManagerEmployees";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add( new SqlParameter( "ManagerID", 3 ) );

using( SqlDataReader reader = cmd.ExecuteReader( CommandBehavior.Default ) )
{
//while (reader.Read())
//{
// Console.WriteLine(reader[3]);
//}
}
}
}
watch.Stop();
Console.WriteLine(
"Running " + count +
" SP's using SQL ExecuteReader took " + watch.ElapsedMilliseconds + " ms");
Console.ReadLine();
}
}


2. DAAB (Data Access Application Block):


public static void SqlSpDAAB()
{
Database adventureWorksDataBase = DatabaseFactory.CreateDatabase( "AdventureWorks" );

Stopwatch watch = new Stopwatch();
watch.Start();

int count = 10000;
for( int i =0; i<count; i++ )
{
using( DBCommandWrapper sp_uspGetManagerEmployees =
adventureWorksDataBase.GetStoredProcCommandWrapper(
"uspGetManagerEmployees" ) )
{
sp_uspGetManagerEmployees.AddInParameter( "@ManagerID", DbType.Int32, 3 );
using( IDataReader dataReader =
adventureWorksDataBase.ExecuteReader( sp_uspGetManagerEmployees ) )
{
//DataSet results =
// adventureWorksDataBase.ExecuteDataSet( sp_uspGetManagerEmployees );
}
}
}
watch.Stop();
Console.WriteLine(
"Running " + count + " SP's using DAAB took " +
watch.ElapsedMilliseconds + " ms");
Console.ReadLine();
}


3. LINQ (using ORM layer produced by SQLMetal.exe - "c:\Program Files\LINQ Preview\Bin\SqlMetal.exe" /server:. /database:AdventureWorks /pluralize /sprocs /code:AdventureWorks.cs):



public static void LinqSPBench()
{
string connectionString =
"Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True";
AdventureWorks adventureWorks = new AdventureWorks( connectionString );

Stopwatch watch = new Stopwatch();
watch.Start();

int count = 10000;
for( int i =0; i<count; i++ )
{
StoredProcedureResult<UspGetManagerEmployeesResult> result =
adventureWorks.UspGetManagerEmployees( 3 );
IEnumerator<UspGetManagerEmployeesResult> enumerator = result.GetEnumerator();
//while( enumerator.MoveNext() )
//{
// Console.WriteLine( enumerator.Current.LastName );
//}
}
watch.Stop();
Console.WriteLine(
"Running " + count +
" SP's using LINQ took " + watch.ElapsedMilliseconds + " ms");
Console.ReadLine();
}


Here are timing results of this benchmarking test:
  • Running 10000 SP's using SQL ExecuteReader took 42806 ms

  • Running 10000 SP's using DAAB took 46443 ms

  • Running 10000 SP's using LINQ took 55136 ms




Results
So, comparing to the raw ADO.NET - DAAB is 8% slower and LINQ is 28% slower.
Comparing to DAAB - LINQ is 18% slower.
CPU usage intensity is about 2% average for raw ADO.NET vs. about 8% for DAAB vs. about 20% for LINQ - order of magnitude worse than raw ADO.NET (CPU graphs captured with perfmon below).


Fig. 1 ADO.NET - CPU usage


Fig. 2 DAAB - CPU usage



Fig. 3 LINQ - CPU usage

In overall - this performance overhead is quite disappointing. I still consider to use LINQ, as we have DAL/BLL servers in our architecture, which we may merely upgrade to faster hardware, while isolating thin-client computers from this performance overhead. I think it's a big challenge for the LINQ team to address its performance.



Thursday, March 22, 2007

Weakest chain amplification principle


What I going to say is actually obvious- but somehow I never thought that the common sense proverb saying "the chain is as weak as its weakest link" is wrong. Really, when you hear it you may visually imagine a chain with a weak link which tears when disruptive force applied to it is much weaker than force needed to disrupt the rest of chain links.
So, what's wrong? The wrong thing is that this proverb usually not being applied to the physical chains. It applies to the chain of circumstances, probabilities or responsibilities.
In fact the chain is much weaker than its weakest link. Really, let's say we are talking about a transportation system in some city. If there is a chance of 50% that your autobus will late and a chance of 50% that your train will late there is a chance of only 25% that you will arrive at time. So, if you're looking at set or related factors where each of them has low failure probability the overall failure probability is much higher. I call it "weakest chain amplification principle".
I think this fact has interesting consequences in a lot of fields. For example in sociology: next time you hear about a 'weak chain' in politic, public sector, police, health system or whatever else you should realize that the overall situation is much worse than this 'weak chain' issue. If some politician is a bit not professional, another one does something a bit not completely legal and another one is a bit dumb all together they form a government that is not a bit weak, but really weak.
Of course - all above applies only when elements or factors are strongly related, i.e. when they are actually bound into 'chain'. And this, in turn, has some interesting implication in creation of complex systems, e.g. in software development. The thing is that, taking a SW development as an example - we may note that any big software complex has its own weak chain (bugs, design mis-considerations, etc), even in its final stage. Then - why at all those big programs are able to work? Considering all said above - it should be impossible to create a stable SW product in principle. How they work then? Well, they work since usually, after some polishing - bugs became kind of sparsely spread around and not related to each other. Theyhappen in certain conditions and with relatively low probability. And then the weakest chain amplification principle doesn't apply to them.

p.s.

Small note there is an obvious connection between above considerations and 'explicit boundaries' and 'autonomous evolution' principles in SOA.

Monday, August 22, 2005

How interception affects performance in .NET




Recently I prepared a lecture on AOP & interception in .NET for my collegues.
As part of a lecture I created a small demo to demonstrate how interception could affect
the performance of the intercepted code. My original estimation was to obtain result
similar to one, obtained in that nice article (slowdown upto 300%
with ~~0,022 microsecond per call).
My test shows a quite different numbers - slowdown by 1099 times with timing of
about ~~19 microsecond per call. The only difference is that I created a complete simple
AOP scenario with context attribute, context property and a message sink (all of a no-op style).

Full test code is below ...



using System;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting;
using System.Diagnostics;
using System.Threading;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Services;
using System.Runtime.Remoting.Contexts;

namespace InteropTimingDemo
{
public class NoOpProperty
: IContextProperty
, IContributeServerContextSink
{
internal NoOpProperty(){}

// IContributeServerContextSink members
public IMessageSink GetServerContextSink(IMessageSink next)
{
return new NoOpSink( next);
}

// IContextProperty members
public string Name { get { return "NoOpProperty"; } }
public bool IsNewContextOK(Context ctx)
{
return true;
}
public void Freeze(Context ctx) { }
}

public class NoOpSink : IMessageSink
{
[ ContextStatic ]
readonly IMessageSink _next;

public NoOpSink(IMessageSink next)
{ this._next = next; }

public IMessage SyncProcessMessage(IMessage r)
{
return _next.SyncProcessMessage(r);
}

public IMessageSink NextSink
{
get{return _next;}
}

public IMessageCtrl AsyncProcessMessage(
IMessage msg, IMessageSink replySink)
{
return null;
}
}

// Define our context-attrbute
[ AttributeUsage(AttributeTargets.Class) ]
public class NoOpAttribute : Attribute, IContextAttribute
{
internal NoOpAttribute(){}

// IContextProperty members
public bool IsContextOK(
Context current, IConstructionCallMessage ctor)
{
object property = current.GetProperty("NoOpProperty");
return (property != null);
}

public void GetPropertiesForNewContext(
IConstructionCallMessage ctor )
{
IContextProperty prop = new NoOpProperty();
ctor.ContextProperties.Add(prop);
}
}


interface ITestClassInterface
{
double DoSomething(double paramA, double paramB);
}

[ NoOp ]
public class InterceptedClass
: ContextBoundObject, ITestClassInterface
{
public double DoSomething(double paramA, double paramB)
{
return paramA * paramB;
}
}

public class OrdinaryClass : ITestClassInterface
{
public double DoSomething(double paramA, double paramB)
{
return paramA * paramB;
}
}


class MainClass
{
[STAThread]
static void Main(string[] args)
{
InterceptedClass interceptedObj = new InterceptedClass();
OrdinaryClass ordinaryObj = new OrdinaryClass();

const int numIterations = 100000;

CTimeMeasurement measure1 = new CTimeMeasurement();
measure1.Start();
//int start = Environment.TickCount;
for( int i=0; i<numIterations; i++ )
{
interceptedObj.DoSomething(i,i+1);
}
//int stop = Environment.TickCount;
measure1.Stop();
Console.WriteLine(
"{0} operations with intercepted object took {1}",
numIterations, measure1.Duration()/*, stop-start*/ );

CTimeMeasurement measure2 = new CTimeMeasurement();
measure2.Start();
//double d = 0.0;
for( int j=0; j<numIterations; j++ )
{
/*d += */ordinaryObj.DoSomething(j,j+1);
}
measure2.Stop();
Console.WriteLine(
"{0} operations with simple object took {1}",
numIterations, measure2.Duration() );

Console.WriteLine(
"Interception slows things down {0} times",
measure1.Duration()/measure2.Duration() );
Console.WriteLine(
"It's about {0} microseconds per call",
measure1.Duration()*1000000/numIterations );

Console.ReadLine();
}
}
}