<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Inquisitive Coder - Davy Brion&#039;s Blog &#187; Performance</title>
	<atom:link href="http://davybrion.com/blog/category/performance/feed/" rel="self" type="application/rss+xml" />
	<link>http://davybrion.com/blog</link>
	<description>Trying to walk that thin line between intelligence and ignorance</description>
	<lastBuildDate>Thu, 29 Jul 2010 20:51:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Why You Shouldn&#8217;t Expose Your Entities Through Your Services</title>
		<link>http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/</link>
		<comments>http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/#comments</comments>
		<pubDate>Mon, 17 May 2010 15:18:43 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Code Quality]]></category>
		<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=2318</guid>
		<description><![CDATA[I sometimes still get questions from people who want to expose their entities through their WCF Services.&#160; Regardless of whether these are entities that are populated through NHibernate or any other ORM, this is just not a good thing to do.&#160; Many people prefer to accept and return entities through their services because they believe [...]]]></description>
			<content:encoded><![CDATA[<p>I sometimes still get questions from people who want to expose their entities through their WCF Services.&#160; Regardless of whether these are entities that are populated through NHibernate or any other ORM, this is just not a good thing to do.&#160; Many people prefer to accept and return entities through their services because they believe this is an easier programming model.&#160; They believe that it takes less work than mapping to DTO’s and that as a whole, this solution is much more manageable.&#160; Rest assured that this is a fallacy.&#160; Any perceived benefit that you’ll get from exposing entities outside of your service layer will only last a <em>very short time</em> and will quickly be dwarfed by added complexity, increased maintenance overhead and a performance overhead which must not be ignored.&#160; </p>
<p>In this post, i’d like to take the chance to explain the downsides to exposing entities through services.&#160; Though i’ll probably miss quite a few of the downsides (feel free to add to the list through comments), the ones i will mention are IMO important enough to take note of.</p>
<p><strong>Exposing entities to clients means your clients are very tightly coupled to your service(s)</strong></p>
<p>Entities are a part of your domain.&#160; These entities in your domain can change for various reasons.&#160; Sometimes because functional changes are required, but quite often also for optimizations (whether they are for performance reasons or to improve the clarity and maintainability of your domain).&#160; Functional changes <em>can </em>impact your clients, though that is not necessarily the case.&#160; Optimizations hardly ever have an impact on your clients (other than possibly improved response times from your service calls obviously).&#160; If your service layer accepts and returns domain entities, each possible change is highly likely to have an impact on your clients.&#160; And this impact is not cheap.&#160; In the best case scenario, it means updating your service contracts, regenerating your service proxies and redeploying your clients.&#160; In the worst case scenario, it means making actual changes to the code of your clients.&#160; And for what? Because of changes that shouldn’t have impacted your clients in the first place? </p>
<p>Ideally, your clients are as dumb as they can be.&#160; They should know as little as possible about the actual <em>implementation</em> of the domain because that implementation is simply not relevant to them.&#160; They should present users with data and give them the option to modify that data, to trigger actions and to perform certain tasks.&#160; They should focus squarely on those tasks and pretty much everything else is typically better suited to be done behind your service layer.&#160; If you build your clients with no real knowledge of the actual domain model, but of DTO’s and possible actions to be performed then you can reduce the level of coupling between your clients and your services substantially. </p>
<p>Many of the people who prefer to expose entities often claim that going for the DTO approach introduces too much extra work and too many extra, seemingly unnecessary classes.&#160; For starters, they don’t want to write code that maps entities to DTO’s.&#160; First of all, the amount of code that this requires is in reality <em>very small</em>, not to mention <em>very easy</em>.&#160; Secondly, you can just as well use a library such as AutoMapper to take that pain away from you.&#160; And contrary to what you might think, there is a big performance gain to be had from returning DTO’s over entities, but i’ll get to that in the next section.</p>
<h5></h5>
<h5></h5>
<p><strong>Entities are hardly ever the most optimal representation of data</strong></p>
<p>I think we can safely say that most applications need to show data in the following 3 ways:</p>
<ul>
<li>In a grid view, either as a total listing of all instances of a certain type of data or the result of a search query or some kind of filtering action </li>
<li>In dropdown controls or anything else that lets users select pieces of data </li>
<li>In edit screens where a piece of data needs to be displayed in its entirety, perhaps even to be modified by the user </li>
</ul>
<p>There are undoubtedly more ways in which data can be presented to the user but i think it’s safe to say that most business applications will certainly rely on the following 3 ways quite heavily.</p>
<p>In the case of a grid view, you’re frequently showing data that is related to more than one entity.&#160; You’ll often need to include the name or the description of some associated entities.&#160; So what exactly is it that you want to do in this situation?&#160; Do you want to return a list of the main entities of the grid view, which all have their required association properties filled in so you can display the columns that you need in the grid view?&#160; Do you actually need all of the properties of these entities (for both the main entities and the associated entities)?&#160; Odds are high that you’re going to be returning a lot more data to the client than you actually need.&#160; And that is what is realistically going to hurt the performance of your system.&#160; Any piece of unnecessary data that you transmit to your clients has a cost associated with it.&#160; The unnecessary data is retrieved from the database.&#160; The entities are then serialized at the service end.&#160; Then they are transmitted to the client.&#160; Then they are deserialized by your client.&#160; All of this is pretty costly, so the more unnecessary data that is included in this operation, the more your performance and the responsiveness of your client (not to mention your database and your server) is impacted negatively.</p>
<p>In the case of dropdown controls or anything else that lets users select pieces of data, you typically only need very few of the properties of that piece of data.&#160; In many cases, the primary key and a name or a description are sufficient.&#160; Do you really need to transmit the entire entity every time for usages like this? Again, keep in mind that all of that extra data that will never be used by your client needs to be retrieved, serialized, transmitted and deserialized again.&#160; Surely, this is an awful waste, no?&#160; </p>
<p>And then there’s the case where a piece of data needs to be displayed in its entirety.&#160; In these cases, you will almost always need all of the properties of the entity that is displayed, but you’ll most often also need to show other data (things that can be selected, or linked to the main entity).&#160; This other data will in most cases fall into the previous category where you’ll only need very little information about the actual entity.&#160; If you’re smart, you’ve chosen the DTO approach to retrieve this data for the data that can be selected, and in that case, you already have all of the infrastructural code in place to project entities or data into DTO’s.&#160; So you might as well reuse it for the main entity as well since you already have the capability to do this.</p>
<p>Always keep in mind that your entities will frequently either contain <em>more data than needed</em>, or <em>less data than needed</em>.&#160; As such, it just doesn’t make much sense to expose entities to your clients since they are hardly ever optimal for client-side usage.&#160; If you really want to think about performance, stop worrying about the supposed cost of mapping to DTO’s (which is truly negligible) and start focusing on <em>what</em> your actually <em>sending</em> to and from your service because this is far more costly than any kind of DTO-mapping really is. </p>
<p><strong>Must your data really come from entities?</strong></p>
<p>If you are displaying data to your user, does that data really need to come from your domain model?&#160; Does it really need to be retrieved by populating a collection of entities to then return them to the client?&#160; Again, keep the <em>form</em> of the data in mind when thinking about this.&#160; In many cases, as i mentioned above, an entity is not the most optimal form of the data that your client needs.&#160; So why even retrieve it through entities? Sure, asking your ORM to retrieve a set of entities based on a set of criteria is often the easiest thing to do, but if the easiest path were the best path, the overall quality of software projects wouldn’t be in the sad state that it’s in today.&#160; If the form of the required data is not identical to the structure of an entity, it’s often far more optimal to simply populate a DTO <em>directly from the data.</em>&#160; With NHibernate, you can easily do this by adding a list of projections to your query and then using a ResultTransformer to populate the DTO’s based on the direct output of the query.&#160; In this case, no entity instance ever needs to be created when you’re just retrieving data, and no extra mapping between the entity and the DTO’s needs to be performed.&#160; Your data access code simply retrieves the resulting data from a query, and puts that data directly in your DTO’s.&#160; There’s no reason why usage of an ORM should prevent you from doing this.&#160;&#160; Once again, this approach will offer far more performance benefits than avoiding DTO mapping at all costs ever can.</p>
<p><strong>What about the behavior of your entities?</strong></p>
<p>Do your entities have any behavior in them?&#160; If not, they are already more of a DTO than a true entity.&#160; In fact, if your entities have no behavior at all, you could even wonder why you’re using an ORM in the first place.&#160; Now, behavior can mean many things.&#160; It could mean lazy loading of associations.&#160; It could mean actual business logic.&#160; Obviously, lazy-loading doesn’t (and shouldn’t!) work client-side, but what about your business logic? Do you have business logic that <em>can </em>be executed client-side? Or is it business logic that should only be executed behind the service layer? If so, how do you make the distinction between this to prevent client-side usage from these entities? Whatever you do, you’re pretty much opening up a can of worms that really is better avoided in the first place.</p>
<p><strong>How are you going to deal with technical issues?</strong></p>
<p>Accepting and returning entities from services introduces a host of technical issues that can be quite substantial.&#160; Serialization and deserialization specifically are issues that you need to be worried about.&#160; If you’re using an ORM which does lazy-loading of associations, this will certainly cause serialization issues that you need to work around.&#160; You can either disable lazy loading, or you can make sure that your entities are always fully initialized (as in: always have their associations fully loaded) before they are sent back to the client.&#160; Disabling lazy-loading <em>will </em>cause performance problems in your service layer, either in places where you don’t expect them to be or in places that you haven’t thought of before it’s too late.&#160; Fully loading your entities and their associates before returning them is another performance nightmare waiting to happen so that’s really not an ideal solution either.&#160; You can try to hook into the serialization process or even the lazy-loading features of your ORM but whatever you do in that case will be a hack that <em>will</em> cause issues sooner or later.&#160; And again, all of these problems can very easily be avoided with a solution which, i hope you realize by now, offers plenty more benefits than any solution where you accept/return entities in your service.</p>
<p><strong>Conclusion</strong></p>
<p>Every single downside to exposing entities through services are issues that i have myself encountered in past projects, either ones i’ve worked on myself, or ones that i’ve seen other people work on.&#160; If that’s not enough for you, then maybe you’ll find it interesting to know that some of the brightest and most respected people (like Udi Dahan and Ayende for instance) in the .NET community also actively recommend against exposing entities through services because of the same downsides that i mentioned, though they could probably give you even more downsides that i forgot to cover in this post.&#160; These downsides are not figments of anyone’s imagination.&#160; They are very real, and you really, really ought to think twice before dismissing this advice.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Using Copy-On-Write In Multithreaded Code To Reduce Locking Overhead</title>
		<link>http://davybrion.com/blog/2010/03/using-copy-on-write-in-multithreaded-code-to-reduce-locking-overhead/</link>
		<comments>http://davybrion.com/blog/2010/03/using-copy-on-write-in-multithreaded-code-to-reduce-locking-overhead/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 15:36:35 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/2010/03/using-copy-on-write-in-multithreaded-code-to-reduce-locking-overhead/</guid>
		<description><![CDATA[I recently posted some code that i asked you to review.&#160; When i posted it, the code had never even executed (that’s right, not even through a test) and i only thought it would do what i needed it to do.&#160; I consider the actual implementation non-obvious (at least for those who don’t know the [...]]]></description>
			<content:encoded><![CDATA[<p>I recently <a href="http://davybrion.com/blog/2010/02/wanna-review-my-code/" target="_blank">posted some code</a> that i asked you to review.&#160; When i posted it, the code had never even executed (that’s right, not even through a test) and i only <em>thought</em> it would do what i needed it to do.&#160; I consider the actual implementation non-obvious (at least for those who don’t know the copy-on-write approach to avoid traditional locking) so i just wanted to hear some reactions to the code from people who didn’t knew the context.&#160; I promised to do a follow-up post to discuss the code in its entirety so here it is.</p>
<p>First, i’ll show the whole class again:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">TenantSessionFactoryManager</span> : <span style="color: #2b91af">ITenantSessionFactoryManager</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ITenantContext</span> tenantContext;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ITenantInfoHolder</span> tenantInfoHolder;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: blue">string</span> mappingAssemblyName;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: blue">object</span> writeLock = <span style="color: blue">new</span> <span style="color: blue">object</span>();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt; sessionFactories;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> TenantSessionFactoryManager(<span style="color: #2b91af">ITenantContext</span> tenantContext, <span style="color: #2b91af">ITenantInfoHolder</span> tenantInfoHolder, <span style="color: blue">string</span> mappingAssemblyName)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.tenantContext = tenantContext;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.tenantInfoHolder = tenantInfoHolder;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.mappingAssemblyName = mappingAssemblyName;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactories = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt;();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ISession</span> CreateSessionForCurrentTenant()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> tenantId = tenantContext.CurrentTenantId;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; CreateSessionFactoryForCurrentTenant();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> sessionFactories[tenantId].OpenSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">void</span> CreateSessionFactoryForCurrentTenant()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">lock</span> (writeLock)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> tenantId = tenantContext.CurrentTenantId;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> connectionString = tenantInfoHolder.GetDatabaseConnectionString(tenantId);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> sessionFactory = <span style="color: blue">new</span> <span style="color: #2b91af">Configuration</span>()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddProperties(<span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { <span style="color: #a31515">&quot;connection.connection_string&quot;</span>, connectionString },</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { <span style="color: #a31515">&quot;cache.region_prefix&quot;</span>, <span style="color: #a31515">&quot;Tenant_&quot;</span> + tenantId }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; })</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddAssembly(mappingAssemblyName)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .BuildSessionFactory();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> newDictionary = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt;(sessionFactories);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; newDictionary[tenantId] = sessionFactory;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactories = newDictionary;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> RemoveSessionFactoryForTenant(<span style="color: #2b91af">Guid</span> tenantId)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">lock</span> (writeLock)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> sessionFactory = sessionFactories[tenantId];</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> newDictionary = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt;(sessionFactories);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; newDictionary.Remove(tenantId);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactories = newDictionary;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactory.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Basically, the purpose of this class is to hold a set of ISessionFactory instances, each of which belongs to a particular tenant in a multi-tenant application.&#160; Tenants can be added on the fly (without restarting the application) and when an ISessionFactory doesn’t exist yet for a particular tenant, it must be created when the first request for an ISession for that tenant comes in.&#160; Obviously, access to the sessionFactories dictionary must be thread-safe since multiple threads will be reading from the dictionary as well as occasionally writing to it.</p>
<p>I considered 3 options to make sure access to the dictionary would be thread-safe:</p>
<ol>
<li>Traditional locking (through the lock statement or the Monitor class) </li>
<li>Using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" target="_blank">ReadWriterLockSlim</a> class </li>
<li>Using the copy-on-write pattern </li>
</ol>
<p>Traditional locking was quickly scratched from the list because that would require me to lock for every read of the dictionary as well as every write.&#160; Now, pretty much every single request requires an NHibernate session which means that pretty much every single request results in a lookup in the sessionFactories dictionary.&#160; If i need to lock for every read, this significantly hurts overall throughput of the system.&#160; </p>
<p>The ReadWriterLockSlim might be a good solution here… after all, the short description of this class in MSDN says this:</p>
<blockquote><p>Represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing.</p>
</blockquote>
<p>Sounds like what i need, right?&#160; But the thing is, i’ve never used the ReadWriterLockSlim class before and it hasn’t really gained my trust yet.&#160; I know that’s a terrible excuse for not using it, but here me out.&#160; While the ReadWriterLockSlim likely reduces locking overhead over traditional locking substantially, there still has to be <em>some</em> overhead for read operations, even if it is small.&#160; In most situations, that small overhead wouldn’t bother me but in this case, that little overhead would be added to pretty much <em>every single request</em> in the system.&#160; Now, writing to a dictionary implies that a new tenant has been added to the system.&#160; In the context of this system, that’s not even gonna happen on a daily basis.&#160; Hell, once a week is probably a best-case estimation and even that is highly optimistic.&#160; So i really don’t want any kind of overhead on read operations when the write operation is only going to happen very occasionally.</p>
<p>That leaves the copy-on-write pattern.&#160; I’ve used it <a href="http://davybrion.com/blog/2009/02/challenge-do-you-truly-understand-this-code/" target="_blank">before</a> with success (though at the time, i didn’t know it was a known pattern) so this approach has already gained my trust.&#160; It basically implies that we don’t do <em>any</em> locking on the read operations, but whenever a write operation occurs we copy the original set of objects, perform the write on the newly copied set and then set the reference of the original set to the newly created and modified instance.&#160; During this whole time, every <em>single</em> read is safe.&#160; Successive reads within the same logical operation however aren’t, so the following code would not be thread-safe:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> sessionFactories[tenantId].OpenSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Because there’s no locking on the reads, the code within the if-block could fail because the sessionFactories reference could be pointing to a new dictionary which no longer contains the element for that key.&#160; </p>
<p>Of course, if you have frequent writes, the overhead of copying the set of objects every time you need to add/remove one might be bigger than you want, so this isn’t a pattern that you should use whenever you need to protect access to a shared resource. For this situation however, i think it’s ideal… though i’d obviously like to hear about better solutions <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now, let’s take a closer look at the pieces of code that perform the write operations.&#160; First, adding a new ISessionFactory to the dictionary:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">void</span> CreateSessionFactoryForCurrentTenant()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">lock</span> (writeLock)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> tenantId = tenantContext.CurrentTenantId;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> connectionString = tenantInfoHolder.GetDatabaseConnectionString(tenantId);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> sessionFactory = <span style="color: blue">new</span> <span style="color: #2b91af">Configuration</span>()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddProperties(<span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { <span style="color: #a31515">&quot;connection.connection_string&quot;</span>, connectionString },</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { <span style="color: #a31515">&quot;cache.region_prefix&quot;</span>, <span style="color: #a31515">&quot;Tenant_&quot;</span> + tenantId }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; })</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddAssembly(mappingAssemblyName)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .BuildSessionFactory();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> newDictionary = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt;(sessionFactories);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; newDictionary[tenantId] = sessionFactory;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactories = newDictionary;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>As you can see, the entire operation is put between a lock on the writeLock object instance.&#160; The downside of this is that creating an ISessionFactory instance is an expensive operation, which means the lock will be held for a long time (could easily be one or more <em>seconds</em>).&#160; Then again, i don’t anticipate this happening frequently so it’s not that big of an issue… especially since reads aren’t being blocked by this anyway.&#160; This approach also prevents the creation of 2 ISessionFactory instances for the same tenant.&#160; Well, unless i missed a bug here :p</p>
<p>Now, once the ISessionFactory instance is created, we create a new Dictionary based on the contents of the old one and then we add the new ISessionFactory instance to it.&#160; After that, we replace the sessionFactories references with the new dictionary and from that point on, every read will use the new dictionary instance.&#160; During this entire operation, no read operation was impacted negatively.&#160; </p>
<p>Now lets take a look at the other write operation, removing an ISessionFactory instance from the dictionary:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> RemoveSessionFactoryForTenant(<span style="color: #2b91af">Guid</span> tenantId)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">lock</span> (writeLock)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> sessionFactory = sessionFactories[tenantId];</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> newDictionary = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt;(sessionFactories);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; newDictionary.Remove(tenantId);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactories = newDictionary;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactory.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>The first if-check, which happens outside of the lock is a bug that i missed but that was pointed out in the comments of the original post.&#160; If CreateSessionFactoryForCurrentTenant and RemoveSessionFactoryForTenant would execute concurrently for the same tenant, it’s possible that the ISessionFactory instance of that tenant is never removed from the dictionary (and also never disposed of…) since the check happens outside of the lock and could be executed before the ISessionFactory of the tenant was added to the dictionary.&#160; In that case, the ISessionFactory instance would stay in the dictionary as long as the application stays up.&#160; This is definitely a race condition that you want to avoid in every other situation though in this case, the odds that we’re simultaneously adding and removing the same tenant are slim to none.&#160; Nevertheless, i don’t want to be accused of promoting race conditions so we’ll make the change anyway <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> RemoveSessionFactoryForTenant(<span style="color: #2b91af">Guid</span> tenantId)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">lock</span> (writeLock)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> sessionFactory = sessionFactories[tenantId];</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> newDictionary = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Guid</span>, <span style="color: #2b91af">ISessionFactory</span>&gt;(sessionFactories);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; newDictionary.Remove(tenantId);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactories = newDictionary;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactory.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Now, as you can see we once again create a new dictionary based on the previous one, then remove the ISessionFactory instance for the current tenant and then we overwrite the sessionFactories instance once again. </p>
<p>Finally, there’s the read operation that i specifically didn’t want suffering from locking overhead:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ISession</span> CreateSessionForCurrentTenant()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> tenantId = tenantContext.CurrentTenantId;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!sessionFactories.ContainsKey(tenantId))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; CreateSessionFactoryForCurrentTenant();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> sessionFactories[tenantId].OpenSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>The only time this code will block is when a new ISessionFactory for the current tenant needs to be created.&#160; Luckily, that only happens once for each tenant.&#160; As i mentioned earlier in the post, using this pattern doesn’t guarantee that successive reads within the same logical operation are thread safe, so there is a bug in here.&#160; If a tenant already has an ISessionFactory instance, it’s possible that the RemoveSessionFactoryForTenant method has been executed between the if-check and accessing the ISessionFactory based on the tenantId.&#160; In that particular scenario, the ISessionFactory instance is no longer in the dictionary which will cause this code to throw an exception.</p>
<p>That’s a bug that i don’t feel like fixing though… Once a tenant has been removed, they are no longer a paying customer.&#160; If they are no longer paying for the software, there is no reason whatsoever why i should care about any possible exceptions they could get while running the software <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Seriously though, if the RemoveSessionFactoryForTenant method is called, users of that tenant won’t even have access to the system anymore so it’s really a non-issue.</p>
<p>Anyways, i think i’ve covered the implementation in more detail than you probably cared for.&#160; So, any thoughts? Are there still issues that i haven’t thought of? Is there another approach that you would use for this specific scenario?</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2010/03/using-copy-on-write-in-multithreaded-code-to-reduce-locking-overhead/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Virtual Method Performance Penalty</title>
		<link>http://davybrion.com/blog/2010/01/virtual-method-performance-penalty/</link>
		<comments>http://davybrion.com/blog/2010/01/virtual-method-performance-penalty/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 16:14:51 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/2010/01/virtual-method-performance-penalty/</guid>
		<description><![CDATA[You often hear/read that one of the reasons why C# methods aren’t virtual by default is because of performance.&#160; Calling a virtual method is more expensive than calling a regular instance method, because the CLR has to determine the correct override to call at runtime, instead of being able to simply call the instance method [...]]]></description>
			<content:encoded><![CDATA[<p>You often hear/read that one of the reasons why C# methods aren’t virtual by default is because of performance.&#160; Calling a virtual method is more expensive than calling a regular instance method, because the CLR has to determine the correct override to call at runtime, instead of being able to simply call the instance method directly.&#160; Another reason why virtual methods are more expensive to call is because they can never be inlined.</p>
<p>Is it really that much more expensive though? I ran a little experiment and i’d like to share the results with you.</p>
<p>Suppose you have the following 2 classes:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyClass</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">long</span> someLong;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> IncreaseLong()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; someLong++;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> VirtualIncreaseLong()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; someLong++;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MyDerivedClass</span> : <span style="color: #2b91af">MyClass</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> VirtualIncreaseLong()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; someLong += 2;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>As you can see, there is no difference between the IncreaseLong and VirtualIncreaseLong methods, except that the latter is virtual and the former is a regular instance method.&#160; According to many people, calling VirtualIncreaseLong instead of IncreaseLong will be more expensive.&#160; I also have a derived class which overrides the VirtualIncreaseLong method with a slightly different implementation.</p>
<p>If we call these methods a bunch of times (like 1000000000 times), we should notice quite a difference according to many people.</p>
<p>I wrote the following test code which calls these methods a bunch of times, times it, and outputs the results.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">class</span> <span style="color: #2b91af">Program</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">const</span> <span style="color: blue">int</span> numberOfTimes = 1000000000;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">static</span> <span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> myObject = <span style="color: blue">new</span> <span style="color: #2b91af">MyClass</span>();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> myDerivedObject = <span style="color: blue">new</span> <span style="color: #2b91af">MyDerivedClass</span>();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// we do this so there&#8217;s no first-time performance cost while timing</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; EnsureThatEverythingHasBeenJitted(myObject);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; EnsureThatEverythingHasBeenJitted(myDerivedObject);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; TestNormalIncreaseMethod(myObject);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; TestVirtualIncreaseMethod(myObject);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; TestNormalIncreaseMethod(myDerivedObject);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; TestVirtualIncreaseMethod(myDerivedObject);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.ReadLine();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">static</span> <span style="color: blue">void</span> EnsureThatEverythingHasBeenJitted(<span style="color: #2b91af">MyClass</span> theObject)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; theObject.IncreaseLong();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; theObject.VirtualIncreaseLong();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">static</span> <span style="color: blue">void</span> TestNormalIncreaseMethod(<span style="color: #2b91af">MyClass</span> theObject)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;calling the IncreaseLong method of type {0} {1} times&quot;</span>, theObject.GetType().Name, numberOfTimes));</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> stopwatch = <span style="color: #2b91af">Stopwatch</span>.StartNew();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">for</span> (<span style="color: blue">var</span> i = 0; i &lt; numberOfTimes; i++)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; theObject.IncreaseLong();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; stopwatch.Stop();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;Elapsed milliseconds: &quot;</span> + stopwatch.ElapsedMilliseconds);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">static</span> <span style="color: blue">void</span> TestVirtualIncreaseMethod(<span style="color: #2b91af">MyClass</span> theObject)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;calling the VirtualIncreaseLong method of type {0} {1} times&quot;</span>, theObject.GetType().Name, numberOfTimes));</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> stopwatch = <span style="color: #2b91af">Stopwatch</span>.StartNew();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">for</span> (<span style="color: blue">var</span> i = 0; i &lt; numberOfTimes; i++)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; theObject.VirtualIncreaseLong();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; stopwatch.Stop();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;Elapsed milliseconds: &quot;</span> + stopwatch.ElapsedMilliseconds);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>The output of running this code might surprise you.&#160; On my machine, i got the following results when the code was compiled in debug mode:</p>
<p><a href="http://davybrion.com/blog/wp-content/uploads/2010/01/manual_compile_debug.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="manual_compile_debug" border="0" alt="manual_compile_debug" src="http://davybrion.com/blog/wp-content/uploads/2010/01/manual_compile_debug_thumb.png" width="753" height="161" /></a> </p>
<p>The difference between calling the regular instance method and the virtual method is quite small.&#160; I’d even say it’s negligible.</p>
<p>When compiling in release mode, i got the following output:</p>
<p><a href="http://davybrion.com/blog/wp-content/uploads/2010/01/manual_compile_optimized.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="manual_compile_optimized" border="0" alt="manual_compile_optimized" src="http://davybrion.com/blog/wp-content/uploads/2010/01/manual_compile_optimized_thumb.png" width="757" height="171" /></a> </p>
<p>I ran the test a bunch of times, and there was no consistent observable performance penalty when calling the virtual methods.&#160; In fact, the virtual methods often performed faster than the regular instance methods and in most cases were equally fast.&#160; I’m not claiming that virtual methods are faster than regular instance methods, but if there really was an extra <em>real-world </em>performance cost associated with virtual methods, it surely should be observable with this test code, no?</p>
<p>Obviously, this test isn’t scientific in any way.&#160; But still, i think it does show that the so called performance cost associated with virtual methods is highly overrated.&#160; There definitely will be cases where virtual methods are more expensive than regular instance methods, but i’m willing to bet that those cases are rare and that the vast majority of .NET developers will never be negatively impacted by it.&#160; </p>
<p>Side note: have you ever noticed that most people who recommend to avoid virtual methods due to their performance cost never put the same emphasis on avoiding the cost of say, frequent remote operations?&#160; Which is odd, since i wouldn’t be surprised if that would be the most common reason for performance problems with .NET applications.&#160; Then again, that’s what you get when the biggest company pushing a platform advocates meaningless performance improvements while at the same time pushing bad architectural decisions/guidelines on the world because the resulting code is supposedly easier to write, use and maintain.</p>
<p>You can download the example code <a href="http://davybrion.com/VirtualMethodsPerformance.zip" target="_blank">here</a> so you can run the test yourself.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2010/01/virtual-method-performance-penalty/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Monitoring Production Performance</title>
		<link>http://davybrion.com/blog/2009/09/monitoring-production-performance/</link>
		<comments>http://davybrion.com/blog/2009/09/monitoring-production-performance/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 19:48:54 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1624</guid>
		<description><![CDATA[It&#8217;s always interesting to know how well your applications perform in production. To get a better view on this, i recently added a bit of performance related logging to the RequestProcessor class of my Request/Response service layer. I have the following 2 loggers set up: .cf { font-family: Consolas; font-size: 9pt; color: black; background: white; [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s always interesting to know how well your applications perform in production.  To get a better view on this, i recently added a bit of performance related logging to the RequestProcessor class of my <a href="http://davybrion.com/blog/2008/07/the-request-response-service-layer/">Request/Response service layer</a>.  I have the following 2 loggers set up:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">readonly</span> <span class="cb2">ILog</span> logger = <span class="cb2">LogManager</span>.GetLogger(<span class="cb1">typeof</span>(<span class="cb2">RequestProcessor</span>));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">readonly</span> <span class="cb2">ILog</span> performanceLogger = <span class="cb2">LogManager</span>.GetLogger(<span class="cb3">&quot;PERFORMANCE&quot;</span>);</p>
</div>
<p></code></p>
<p>And here&#8217;s a simplified version of the Process method:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: green; }
.cb4 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb2">Response</span>[] Process(<span class="cb1">params</span> <span class="cb2">Request</span>[] requests)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (requests == <span class="cb1">null</span>) <span class="cb1">return</span> <span class="cb1">null</span>;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> responses = <span class="cb1">new</span> <span class="cb2">List</span>&lt;<span class="cb2">Response</span>&gt;(requests.Length);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> batchStopwatch = <span class="cb2">Stopwatch</span>.StartNew();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">foreach</span> (<span class="cb1">var</span> request <span class="cb1">in</span> requests)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">try</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">using</span> (<span class="cb1">var</span> handler = (<span class="cb2">IRequestHandler</span>)<span class="cb2">IoC</span>.Container.Resolve(GetHandlerTypeFor(request)))</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> requestStopwatch = <span class="cb2">Stopwatch</span>.StartNew();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">try</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb3">// NOTE: the real code has a lot more stuff in this block for dealing with</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb3">// failed requests etc...</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; responses.Add(GetResponseFromHandler(request, handler));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">finally</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; requestStopwatch.Stop();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (requestStopwatch.ElapsedMilliseconds &gt; 100)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; performanceLogger.Warn(<span class="cb1">string</span>.Format(<span class="cb4">&quot;Performance warning: {0}ms for {1}&quot;</span>, </p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; requestStopwatch.ElapsedMilliseconds, handler.GetType().Name));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">IoC</span>.Container.Release(handler);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">catch</span> (<span class="cb2">Exception</span> e)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb3">// NOTE: every single thrown exception in the service layer (and everything below it)</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb3">// is caught here and logged only once</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; logger.Error(e);&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp; </p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">throw</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; batchStopwatch.Stop();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (batchStopwatch.ElapsedMilliseconds &gt; 200)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">var</span> builder = <span class="cb1">new</span> <span class="cb2">StringBuilder</span>();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">foreach</span> (<span class="cb1">var</span> request <span class="cb1">in</span> requests)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; builder.Append(request.GetType().Name + <span class="cb4">&quot;, &quot;</span>);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; builder.Remove(builder.Length - 2, 2);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; performanceLogger.Warn(<span class="cb1">string</span>.Format(<span class="cb4">&quot;Performance warning: {0}ms for the following batch: {1}&quot;</span>, </p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; batchStopwatch.ElapsedMilliseconds, builder));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> responses.ToArray();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The part that is simplified is simply the part that deals with getting the actual responses for each request, including how to deal with failed requests and how to handle subsequent requests in the batch.  It&#8217;s not relevant to this post and it only clutters the code more so i left that out.  But anyways, the interesting part here is the performance logging.  Ok, the code itself isn&#8217;t interesting but what you get out of it is pretty nice.  Each single request that takes more than 100 milliseconds is logged.  Also, each batch of requests that takes more than 200 milliseconds is logged.  Both of these &#8216;events&#8217; are logged to the performance logger which, in our case, is set up to use a different logfile than the typical error log. </p>
<p>Which gives us some interesting looking data, like this:</p>
<p><code><br />
WARN 2009-09-05 08:58:45 - Performance warning: 122ms for GetOpportunityCardHandler<br />
WARN 2009-09-05 09:00:45 - Performance warning: 159ms for GetCompanyCardHandler<br />
WARN 2009-09-05 09:01:23 - Performance warning: 187ms for GetOpportunityCardHandler<br />
WARN 2009-09-05 09:01:32 - Performance warning: 155ms for GetCompanyCardHandler<br />
WARN 2009-09-05 09:01:41 - Performance warning: 189ms for GetOpportunityCardHandler<br />
WARN 2009-09-05 09:01:41 - Performance warning: 336ms for the following batch: GetSalesTaskCardRequest, GetContactCardRequest, GetOpportunityCardRequest, GetCompanyCardRequest<br />
</code></p>
<p>336ms for a single batch of requests is rather slow, and if we see this output regularly in the logfile, we definitely know that these specific request handlers really need to be optimized because we can be pretty sure that is too slow in the real production environment.</p>
<p>It&#8217;s also useful to identify single request handlers who could use some optimization:</p>
<p><code><br />
WARN 2009-09-04 02:55:40 - Performance warning: 108ms for PersistIssueHandler<br />
WARN 2009-09-04 05:54:50 - Performance warning: 148ms for PersistTimesheetEntryHandler<br />
</code></p>
<p>We&#8217;ve already deployed this for an internal version of one of our applications, which helped us identify some parts that we really needed to optimize before our next external deployment (for our customers).  Even better, when we deploy for our customers, each log entry will also contain the name of the tenant (customer) for which the performance warning was generated.  Which will only make it easier for us to identify real hotspots, based on real usage from our customers, and try to optimize them as soon as possible, preferably before customers start complaining about specific parts.</p>
<p>I&#8217;m sure some of you are already doing something similar, but i&#8217;m also pretty sure that most of you aren&#8217;t doing this yet.  I&#8217;d definitely recommend doing something like this, because it definitely makes it easier to fix _real_ performance issues instead of the theoretical ones <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/09/monitoring-production-performance/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Reducing ViewState Size</title>
		<link>http://davybrion.com/blog/2009/09/reducing-viewstate-size/</link>
		<comments>http://davybrion.com/blog/2009/09/reducing-viewstate-size/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 12:56:53 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1593</guid>
		<description><![CDATA[I dislike ViewState as much as the next guy, but when you&#8217;re working with ASP.NET WebForms, you just can&#8217;t avoid it. In some cases, the size of the ViewState can become so big that it significantly increases the load time of pages due to the extra bandwidth consumption. The correct solution would obviously be to [...]]]></description>
			<content:encoded><![CDATA[<p>I dislike ViewState as much as the next guy, but when you&#8217;re working with ASP.NET WebForms, you just can&#8217;t avoid it.  In some cases, the size of the ViewState can become so big that it significantly increases the load time of pages due to the extra bandwidth consumption.  The correct solution would obviously be to reduce the size of the ViewState in those pages as much as you can, but it&#8217;s not always feasible to do so.  So we wanted a more general &#8216;solution&#8217;, and i found <a href="http://aspadvice.com/blogs/mamanzes_blog/archive/2006/08/27/Save-some-space_2C00_-compress-that-ViewState.aspx">this post</a> which discusses compressing the ViewState before you send it to the client and decompressing it when the client sends it back.  We used pretty much the same approach, but with some differences.</p>
<p>First of all, ViewState is persisted in the resulting HTML page through an IStateFormatter object.  We&#8217;ll provide our own CompressedStateFormatter which implements the IStateFormatter interface, and uses the standard IStateFormatter that ASP.NET uses:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">CompressedStateFormatter</span> : <span style="color: #2b91af;">IStateFormatter</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">IStateFormatter</span> actualFormatter;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> CompressedStateFormatter(<span style="color: #2b91af;">IStateFormatter</span> actualFormatter)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">this</span>.actualFormatter = actualFormatter;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">string</span> Serialize(<span style="color: blue;">object</span> state)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">string</span> decompressedState = actualFormatter.Serialize(state);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">MemoryStream</span> memoryStream = <span style="color: blue;">new</span> <span style="color: #2b91af;">MemoryStream</span>())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">Stream</span> zipStream = <span style="color: blue;">new</span> <span style="color: #2b91af;">GZipStream</span>(memoryStream, <span style="color: #2b91af;">CompressionMode</span>.Compress))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">StreamWriter</span> writer = <span style="color: blue;">new</span> <span style="color: #2b91af;">StreamWriter</span>(zipStream))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; writer.Write(decompressedState);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> <span style="color: #2b91af;">Convert</span>.ToBase64String(memoryStream.ToArray());</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">object</span> Deserialize(<span style="color: blue;">string</span> serializedState)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">byte</span>[] data = <span style="color: #2b91af;">Convert</span>.FromBase64String(serializedState);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">MemoryStream</span> memoryStream = <span style="color: blue;">new</span> <span style="color: #2b91af;">MemoryStream</span>(data))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">Stream</span> zippedStream = <span style="color: blue;">new</span> <span style="color: #2b91af;">GZipStream</span>(memoryStream, <span style="color: #2b91af;">CompressionMode</span>.Decompress))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">StreamReader</span> reader = <span style="color: blue;">new</span> <span style="color: #2b91af;">StreamReader</span>(zippedStream))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> actualFormatter.Deserialize(reader.ReadToEnd());</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The idea is very simple: when the Serialize method is called, we first call the real formatter&#8217;s Serialize method, compress its return value and then return the Base64-encoded string of the compressed serialized state.  And in the Deserialize method, we do the exact opposite: we first decompress the Base64-encoded string and then we use the real formatter to deserialize the actual ViewState.</p>
<p>In Mamanze&#8217;s example, he checks to see if the compressed version is actually smaller than the decompressed version and if so, uses the decompressed version instead of the compressed one.  And when decompressing he first checks to see if it&#8217;s a compressed or decompressed version and obviously only decompresses in case of a compressed version.  The only page where i found the compressed version of the ViewState to be larger than the decompressed version was in our log in page, so i just got rid of that piece of the code.</p>
<p>Now we still have to plug this into ASP.NET&#8217;s behavior somehow&#8230; first we add a pagestate.browser file to the App_Browsers folder of your web application (if it doesn&#8217;t exist, just create it) with the following content:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">browsers</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &lt;</span><span style="color: #a31515;">browser</span><span style="color: blue;"> </span><span style="color: red;">refID</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">Default</span>&quot;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">controlAdapters</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span style="color: #a31515;">adapter</span><span style="color: blue;"> </span><span style="color: red;">controlType</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">System.Web.UI.Page</span>&quot;<span style="color: blue;"> </span><span style="color: red;">adapterType</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">Our.Application.CompressedPageStateAdapter</span>&quot;<span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;/</span><span style="color: #a31515;">controlAdapters</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &lt;/</span><span style="color: #a31515;">browser</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">browsers</span><span style="color: blue;">&gt;</span></p>
</div>
<p></code></p>
<p>The CompressedPageStateAdapter looks like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">CompressedPageStateAdapter</span> : <span style="color: #2b91af;">PageAdapter</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: #2b91af;">PageStatePersister</span> GetStatePersister()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">CompressedHiddenFieldPageStatePersister</span>(Page);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>And the CompressedHiddenFieldPageStatePersister class looks like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">CompressedHiddenFieldPageStatePersister</span> : <span style="color: #2b91af;">HiddenFieldPageStatePersister</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> CompressedHiddenFieldPageStatePersister(<span style="color: #2b91af;">Page</span> page) : <span style="color: blue;">base</span>(page)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">FieldInfo</span> field = <span style="color: blue;">typeof</span>(<span style="color: #2b91af;">PageStatePersister</span>).GetField(<span style="color: #a31515;">&quot;_stateFormatter&quot;</span>, <span style="color: #2b91af;">BindingFlags</span>.NonPublic | <span style="color: #2b91af;">BindingFlags</span>.Instance);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// retrieving this property instantiates the default IStateFormatter</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> defaultFormatter = <span style="color: blue;">base</span>.StateFormatter; </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> formatter = <span style="color: blue;">new</span> <span style="color: #2b91af;">CompressedStateFormatter</span>(defaultFormatter);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; field.SetValue(<span style="color: blue;">this</span>, formatter);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The HiddenFieldPageStatePersister is the class that ASP.NET WebForms will use by default to store your ViewState into a hidden field in the resulting HTML.  By default, the HiddenFieldPageStatePersister uses the default IStateFormatter type that ASP.NET uses, which only uses Base64 encoding but no compression.  Unfortunately, there is no clean way to instruct ASP.NET to use a different implementation for IStateFormatter, so we need to use a bit of reflection to overwrite the value of HiddenFieldPageStatePersister&#8217;s _stateFormatter field.  Luckily, this also enables us to first get the value of the StateFormatter property so we can pass this reference (which is the &#8216;real&#8217; formatter) to our CompressedStateFormatter.</p>
<p>And that is all there is to it&#8230; all of your pages will now use this CompressedHiddenFieldPageStatePersister so you get the benefit of ViewState compression in each of your pages.  You can also do this selectively if you want, by not using the pagestate.browser file and overriding the PageStatePersister property of your ASPX page:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: #2b91af;">CompressedHiddenFieldPageStatePersister</span> persister;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">override</span> <span style="color: #2b91af;">PageStatePersister</span> PageStatePersister</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">get</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (persister == <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; persister = <span style="color: blue;">new</span> <span style="color: #2b91af;">CompressedHiddenFieldPageStatePersister</span>(<span style="color: blue;">this</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> persister;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>This way, only the pages that contain this code will use the CompressedHiddenFieldPageStatePersister.</p>
<p>Instead of inheriting from HiddenFieldPageStatePersister, you could also inherit from SessionPageStatePersister.  SessionPageStatePersister will store your ViewState in the HttpSessionState, and will only include a little bit of ViewState in your HTML page instead of everything.  But you do need to be aware of the fact that using the CompressedStateFormatter when inheriting from SessionPageStatePersister will only result in compressing the little bit of ViewState that is included in the HTML, and <strong>not</strong> the ViewState that is stored in the HttpSessionState. </p>
<p>In case you&#8217;re wondering: why should i use this instead of using typical HTTP compression on the IIS level?  I believe it has a couple of advantages to HTTP compression.  First of all, AFAIK, HTTP compression does not have any benefit on postbacks.  And since ViewState is always posted back to the server, this can make a pretty big difference.  Also, with this approach, the client will not have to decompress the entire ViewState (which isn&#8217;t used client-side anyway) and the browser doesn&#8217;t have to waste time on it in general.</p>
<p>I haven&#8217;t used this in production yet, but i will very soon&#8230; unless someone knows of a good reason why i shouldn&#8217;t <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/09/reducing-viewstate-size/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Of Course NHibernate Is Slow When You Use It Incorrectly</title>
		<link>http://davybrion.com/blog/2009/08/of-course-nhibernate-is-slow-when-you-use-it-incorrectly/</link>
		<comments>http://davybrion.com/blog/2009/08/of-course-nhibernate-is-slow-when-you-use-it-incorrectly/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 20:48:36 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1511</guid>
		<description><![CDATA[Just saw the following post where the performance of NHibernate and Entity Framework is compared for a couple of different operations. Spoiler alert: NHibernate loses. As it typically does in these kinds of &#8216;benchmarks&#8217; or &#8216;comparisons&#8217; that seem to pop up frequently lately. For some reason, a lot of people seem to think that opening [...]]]></description>
			<content:encoded><![CDATA[<p>Just saw the following <a href="http://gregdoesit.com/2009/08/nhibernate-vs-entity-framework-a-performance-test/">post</a> where the performance of NHibernate and Entity Framework is compared for a couple of different operations.  Spoiler alert: NHibernate loses.  As it typically does in these kinds of &#8216;benchmarks&#8217; or &#8216;comparisons&#8217; that seem to pop up frequently lately.</p>
<p>For some reason, a lot of people seem to think that opening an NHibernate session and performing thousands of operations is a valid use case.  It&#8217;s not.  Far from it actually.  And with all of the features that NHibernate offers, it can&#8217;t possibly perform well in such a scenario.  See, an NHibernate session is a <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">unit of work</a>.  A unit of work is a business transaction which is typically short and small, but it should never be something huge.  Your DBA probably won&#8217;t appreciate huge database transactions on the database either.</p>
<p>Whenever you load an object through NHibernate, it will be tracked by the session that loaded it.  That means that the NHibernate session keeps a reference to it, and performs a series of checks on it periodically, depending on what you&#8217;re doing and some configuration settings such as the FlushMode.  For instance, suppose you&#8217;ve loaded a hundred different entities in one session.  If the FlushMode is set to automatic, it means that NHibernate will perform a dirty check for each entity associated with the session before each query is executed.  The more entity instances you&#8217;ve loaded, the longer this takes (obviously).  If you take this to an extreme level, like loading thousands of entities like most of these &#8216;benchmarks&#8217; do, performance will naturally be horrible.</p>
<p>Each entity instance is also stored in the first level (or session level) cache.  That means that whenever you retrieve a row from the database, NHibernate will check if an instance of that row already exists in the first level cache.  Again, the more instances you&#8217;ve loaded, the larger the overhead of this will be.   There are also a lot of possible extension points where you can plug in custom logic.  Again, there is a very minor cost that comes with this extensibility and as you can expect, that minor cost can add up to something much more noticable once you start dealing with an unreasonably large number of instances in your session.</p>
<p>Always keep in mind that an ORM (and this goes for every ORM) is most suitable for <a href="http://en.wikipedia.org/wiki/OLTP">OLTP</a>.  Using an ORM for batch processing jobs or large data processing operations in general is simply put a bad idea.  And they will never perform as well as other solutions in these scenarios.  So please don&#8217;t bother even benchmarking ORM performance in non OLTP usage because it quite simply doesn&#8217;t make sense to do so, and the results will be completely untrustworthy anyway.</p>
<p>An ORM can offer you nice performance gains in OLTP scenarios simply by trying to minimize database connectivity, minimizing the number of database operations, and relatively sane caching usage.  Unfortunately, these are aspects that are never tested in these &#8216;benchmarks&#8217; or &#8216;comparisons&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/08/of-course-nhibernate-is-slow-when-you-use-it-incorrectly/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Avoid Using NHibernate With NUnit 2.4.6</title>
		<link>http://davybrion.com/blog/2009/06/avoid-using-nhibernate-with-nunit-2-4-6/</link>
		<comments>http://davybrion.com/blog/2009/06/avoid-using-nhibernate-with-nunit-2-4-6/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 17:35:42 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1432</guid>
		<description><![CDATA[We just spent about 2 hours trying to find out why our NHibernate tests were about 10x slower on our build server than they were on our local machines. I had noticed lately that the build for one of our projects was taking longer and longer but i hadn&#8217;t really timed the difference. This project [...]]]></description>
			<content:encoded><![CDATA[<p>We just spent about 2 hours trying to find out why our NHibernate tests were about 10x slower on our build server than they were on our local machines.  I had noticed lately that the build for one of our projects was taking longer and longer but i hadn&#8217;t really timed the difference.  This project has about 1200 tests that use NHibernate and they run in about 45-60 seconds on my local machine.  It turns out they took around 15 <strong>minutes</strong> on the buildserver when running them through TeamCity.</p>
<p>I logged into the buildserver and ran the tests manually using nunit&#8217;s console runner (with an NUnit-2.4.7 build that i happened to have installed somewhere on the machine) and they only took about 45 seconds.  After a lot of guesswork and screwing around, it turned out that we never modified our base build script (why yes, i do believe in build script inheritance) to use a newer version of NUnit.  We set up the buildserver about 1 year ago, and at that time, the latest stable NUnit version that TeamCity supported was NUnit 2.4.6.  Our base build script was still referring to NUnit 2.4.6, which apparently <a href="http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/nhibernate-nunit-2-4-6-and-log4net">sets log4net to use debug level logging</a>.  Now, NHibernate logs a huge amount of information at the debug level, so this turned out to slow down all of our builds that had NHibernate tests.</p>
<p>We changed the the 2.4.6 version in our script to 2.4.7 and the build time of this particular project decreased from around 50 minutes to about 35 minutes.  Yes, that&#8217;s still a lot but this is a huge project with a lot of legacy tests and the entire build process is pretty complex.  Other projects went from build times from around 7 minutes to about 2 minutes.</p>
<p>That&#8217;s a pretty nice improvement for simply changing a &#8220;6&#8243; to a &#8220;7&#8243; <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/06/avoid-using-nhibernate-with-nunit-2-4-6/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Keep An Eye On Those Indexes</title>
		<link>http://davybrion.com/blog/2009/05/keep-an-eye-on-those-indexes/</link>
		<comments>http://davybrion.com/blog/2009/05/keep-an-eye-on-those-indexes/#comments</comments>
		<pubDate>Thu, 21 May 2009 12:14:57 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1387</guid>
		<description><![CDATA[We have a multi-tenant application, where each tenant has its own database. We recently were informed about a particular performance problem that one tenant (which we&#8217;ll refer to as Tenant A) was experiencing in every screen where data of a certain type needed to be shown. None of the other tenants experienced this problem though. [...]]]></description>
			<content:encoded><![CDATA[<p>We have a multi-tenant application, where each tenant has its own database. We recently were informed about a particular performance problem that one tenant (which we&#8217;ll refer to as Tenant A) was experiencing in every screen where data of a certain type needed to be shown.  None of the other tenants experienced this problem though.</p>
<p>We tracked down the query that was causing the bad performance and ran it on the database of Tenant B.  Tenant B actually had a lot more data in the main table that was used in the query and the query executed immediately whereas it took about 25 seconds to complete for Tenant A.   So the query runs fast on another database that actually has more data&#8230; at this point i was convinced that it had to be related to indexes.</p>
<p>Turns out that someone recently ran an import process to import a bunch of data in Tenant A&#8217;s database. I know very little about databases, but one thing i&#8217;ve seen time and time again (with both Oracle and SQL Server) is that you really need to make sure that your indexes are in good shape after any process that performs a lot of inserts (or removals).   A couple of years ago, i had a very intensive nightly import process for a particular project that used an Oracle database.  As time went on, the application&#8217;s queries became painfully (unacceptably even) slow.  I managed to restore the performance of those queries by simply instructing Oracle to recalculate all of the statistics of the indexes of tables that were affected heavily during the nightly import.</p>
<p>With that in mind, we simply rebuilt the indexes for Tenant A&#8217;s database, and the same query that took 25 seconds completed almost instantly from then on.  Now, we did had a weekly job running on that database server to keep the indexes in a healthy shape but that job didn&#8217;t really do a good umm&#8230; job of it, apparently.  </p>
<p>Lessons learned: make sure that you:</p>
<ul>
<li>Have a proper maintenance job set up which keeps your indexes healthy and schedule it to run regularly</li>
<li>Run that job manually if you need to perform a manual import process</li>
<li>Execute that job in an automated fashion whenever an intensive automated import process has completed</li>
</ul>
<p>Oh, and consult with your DBA&#8217;s or at least people who know what they&#8217;re doing when it comes to your particular database on how to keep those indexes healthy.  In this case, we rebuilt them.  In other cases it&#8217;s sufficient to recalculate the statistics&#8230; i&#8217;m not sure which way is the best but you should at least keep an eye on this possible problem <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/05/keep-an-eye-on-those-indexes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using The Guid.Comb Identifier Strategy</title>
		<link>http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy/</link>
		<comments>http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy/#comments</comments>
		<pubDate>Thu, 21 May 2009 12:00:31 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1238</guid>
		<description><![CDATA[As you may have read by now, it&#8217;s a good idea to avoid identity-style identifier strategies with ORM&#8217;s. One of the better alternatives that i kinda like is the guid.comb strategy. Using regular guids as a primary key value leads to fragmented indexes (due to the randomness of the guid&#8217;s value) which leads to bad [...]]]></description>
			<content:encoded><![CDATA[<p>As you may have read by now, it&#8217;s a good idea to <a href="http://ayende.com/Blog/archive/2009/03/20/nhibernate-avoid-identity-generator-when-possible.aspx">avoid identity-style identifier strategies</a> with ORM&#8217;s.  One of the better alternatives that i kinda like is the guid.comb strategy.  Using regular guids as a primary key value leads to fragmented indexes (due to the randomness of the guid&#8217;s value) which leads to bad performance.  This is a problem that the guid.comb strategy can solve quite easily for you.</p>
<p>If you want to learn how the guid.comb strategy really works, be sure to check out <a href="http://www.informit.com/articles/article.aspx?p=25862">Jimmy Nilsson&#8217;s article on it</a>. Basically, this strategy generates sequential guids which solves the fragmented index issue.  You can generate these sequential guids in your database, but the downside of that is that your ORM would still need to insert each record seperately and fetch the generated primary key value each time.  NHibernate includes the guid.comb strategy which will generate the sequential guids before actually inserting the records in your database.</p>
<p>This obviously has some great benefits: </p>
<ul>
<li>you don&#8217;t have to hit the database immediately whenever a record needs to be inserted</li>
<li>you don&#8217;t need to retrieve a generated primary key value when a record was inserted</li>
<li>you can batch your insert statements</li>
</ul>
<p>Let&#8217;s see how we can use this with NHibernate.  First of all, you need to map the identifier of your entity like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #a31515; }
.cb3 { color: red; }
</style>
<div class="cf">
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">id</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Id</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">Id</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">guid</span>&quot;<span class="cb1"> &gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &nbsp; &lt;</span><span class="cb2">generator</span><span class="cb1"> </span><span class="cb3">class</span><span class="cb1">=</span>&quot;<span class="cb1">guid.comb</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;/</span><span class="cb2">id</span><span class="cb1">&gt;</span></p>
</div>
<p></code></p>
<p>And that&#8217;s actually all you have to do.  You don&#8217;t have to assign the primary key values or anything like that.  You don&#8217;t need to worry about them at all.  </p>
<p>Take a look at the following test:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: blue; }
.cb3 { color: #a31515; }
.cb4 { color: green; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span class="cb1">Test</span>]</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">public</span> <span class="cb2">void</span> InsertsAreOnlyExecutedAtTransactionCommit()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">var</span> insertCountBefore = sessionFactory.Statistics.EntityInsertCount;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">using</span> (<span class="cb2">var</span> session = sessionFactory.OpenSession())</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">using</span> (<span class="cb2">var</span> transaction = session.BeginTransaction())</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">for</span> (<span class="cb2">int</span> i = 0; i &lt; 50; i++)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">var</span> category = <span class="cb2">new</span> <span class="cb1">ProductCategory</span>(<span class="cb2">string</span>.Format(<span class="cb3">&quot;category {0}&quot;</span>, i + 1));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// at this point, the entity doesn't have an ID value yet</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreEqual(<span class="cb1">Guid</span>.Empty, category.Id);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; session.Save(category);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// now the entity has an ID value, but we still haven't hit the database yet</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreNotEqual(<span class="cb1">Guid</span>.Empty, category.Id);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// just verifying that we haven't hit the database yet to insert the new categories</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreEqual(insertCountBefore, sessionFactory.Statistics.EntityInsertCount);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; transaction.Commit();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// only now have the recors been inserted</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreEqual(insertCountBefore + 50, sessionFactory.Statistics.EntityInsertCount);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Interesting, no? The entities have an ID value after they have been &#8216;saved&#8217; by NHibernate.  But they haven&#8217;t actually been saved to the database yet though.  NHibernate always tries to wait as long as possible to hit the database, and in this case it only needs to hit the database when the transaction is committed.  If you&#8217;ve enabled <a href="http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/">batching of DML statements</a>, you could severly reduce the number of times you need to hit the database in this scenario.</p>
<p>And in case you&#8217;re wondering, the generated guids look like this:</p>
<p>81cdb935-d371-4285-9dcb-9bdb0122f25f<br />
a44baf99-58e9-4ad7-9a59-9bdb0122f25f<br />
a88300c2-6d64-4ae3-a55b-9bdb0122f25f<br />
032c7884-da2f-4568-b505-9bdb0122f25f<br />
&#8230;.<br />
70d7713c-b38d-4341-953d-9bdb0122f25f</p>
<p>Notice the last part of the guids&#8230; this is what prevents the index fragmentation.</p>
<p>Obviously, this particular test is not a realistic scenario but i&#8217;m sure you understand how much of an improvement this identifier strategy could provide throughout an entire application.  The only downside (IMO) is that guid&#8217;s aren&#8217;t really human readable so if that is important to you, you should probably look into other identifier strategies.  The HiLo strategy would be particularly interesting in that case, but we&#8217;ll cover that in a later post <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Put Performance Concerns Into Perspective</title>
		<link>http://davybrion.com/blog/2009/04/put-performance-concerns-into-perspective/</link>
		<comments>http://davybrion.com/blog/2009/04/put-performance-concerns-into-perspective/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 14:58:03 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1318</guid>
		<description><![CDATA[There is a reported performance issue with NHibernate that i wanted to look into. The reported issue was related to retrieving objects through a generically typed List or through an IList reference. The following code simulates the issue: .cf { font-family: Consolas; font-size: 9pt; color: black; background: white; } .cl { margin: 0px; } .cb1 [...]]]></description>
			<content:encoded><![CDATA[<p>There is a reported <a href="http://nhjira.koah.net/browse/NH-1079">performance issue</a> with NHibernate that i wanted to look into.  The reported issue was related to retrieving objects through a generically typed List or through an IList reference.  </p>
<p>The following code simulates the issue:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">class</span> <span class="cb2">MyClass</span> {}</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">class</span> <span class="cb2">Program</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">static</span> <span class="cb1">void</span> Main(<span class="cb1">string</span>[] args)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">List</span>&lt;<span class="cb2">MyClass</span>&gt; list = <span class="cb1">new</span> <span class="cb2">List</span>&lt;<span class="cb2">MyClass</span>&gt;();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Stopwatch</span> stopwatch = <span class="cb2">Stopwatch</span>.StartNew();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">for</span> (<span class="cb1">int</span> i = 0; i &lt; 100000; i++)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; list.Add(<span class="cb1">new</span> <span class="cb2">MyClass</span>());</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Stop();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;Elapsed ms: &quot;</span> + stopwatch.ElapsedMilliseconds);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">IList</span> iList = <span class="cb1">new</span> <span class="cb2">List</span>&lt;<span class="cb2">MyClass</span>&gt;();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch = <span class="cb2">Stopwatch</span>.StartNew();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">for</span> (<span class="cb1">int</span> i = 0; i &lt; 100000; i++)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; iList.Add(<span class="cb1">new</span> <span class="cb2">MyClass</span>());</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Stop();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.WriteLine(<span class="cb3">&quot;Elapsed ms: &quot;</span> + stopwatch.ElapsedMilliseconds);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">Console</span>.ReadLine();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The only difference between both Add operations is that in the first case, the typed Add method of the generically typed List reference is called.  In the second case, the untyped Add method of the generically typed List is called through the IList reference.</p>
<p>On my slow Macbook, the first Add operation typically took between 10 and 20 ms.  The second Add operation typically took almost twice as long as the first Add operation.  As you can see, that is a very minor performance issue, and it actually is only consistently noticeable once you&#8217;re dealing with 100000 elements.  At 50000 elements, both operations typically take the same amount of time with only minor variations in performance on certain runs.</p>
<p>So yes, once you&#8217;re dealing with a large enough set of elements, there is indeed a performance difference.  But it&#8217;s extremely minor and the extra cost of the Add operation is most definitely <strong>the least of your concerns if you&#8217;re retrieving that many entity instances through an ORM.</strong>  The extra amount of memory that needs to be used for those entities and the extra cost of pulling all of that data over the wire is what&#8217;s really going to bite you, not the extra cost of the Add operation <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/put-performance-concerns-into-perspective/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Transparent Query Batching Through Your Repository</title>
		<link>http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/</link>
		<comments>http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 11:35:52 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1200</guid>
		<description><![CDATA[All of our projects that use NHibernate (which is all of them except those where the customer explicitly doesn&#8217;t want us to use it or where it wouldn&#8217;t make sense to use it) use the same Repository implementation. After the Future and FutureValue queries were added to NHibernate, i modified the implementation of that Repository [...]]]></description>
			<content:encoded><![CDATA[<p>All of our projects that use NHibernate (which is all of them except those where the customer explicitly doesn&#8217;t want us to use it or where it wouldn&#8217;t make sense to use it) use the same <a href="http://davybrion.com/blog/2008/06/data-access-with-nhibernate/">Repository implementation</a>.  After the <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">Future</a> and <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries-part-2/">FutureValue</a> queries were added to NHibernate, i modified the implementation of that Repository class.  </p>
<p>Two of the FindAll methods now look like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IEnumerable</span>&lt;T&gt; FindAll()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> Session.CreateCriteria&lt;T&gt;().Future&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IEnumerable</span>&lt;T&gt; FindAll(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).Future&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The only thing i changed in those methods is calling the Future method, instead of the List method.  That&#8217;s it.  All of our specific Find-methods (those that execute specific queries) pass through the FindAll(DetachedCriteria criteria) method so they all benefit from this change.  </p>
<p>That means that all of our queries are suddenly batched transparently whenever possible, without impacting any of the calling code.  And that is pretty nice if you ask me.  Batching queries can offer a substantial performance benefit, and we didn&#8217;t even have to change any of the calling code to achieve it.  </p>
<p>Obviously, this only works for the queries that return IEnumerables (in our case, that&#8217;s every query that doesn&#8217;t return a single value).  I also added a few more methods to enable query batching for queries that return a single entity, or a scalar value (i kept the original methods in this code snippet as well so you can see the difference):</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> T FindOne(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).UniqueResult&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IFutureValue</span>&lt;T&gt; FindFutureOne(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).FutureValue&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
</div>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> K GetScalar&lt;K&gt;(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> (K)criteria.GetExecutableCriteria(Session).UniqueResult();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IFutureValue</span>&lt;K&gt; GetFutureScalar&lt;K&gt;(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).FutureValue&lt;K&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
</div>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">int</span> Count(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> <span class="cb2">Convert</span>.ToInt32(QueryCount(criteria).GetExecutableCriteria(Session).UniqueResult());</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IFutureValue</span>&lt;<span class="cb1">int</span>&gt; FutureCount(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> QueryCount(criteria).GetExecutableCriteria(Session).FutureValue&lt;<span class="cb1">int</span>&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
</div>
<p></code></p>
<p>So let&#8217;s recap.  Queries that return IEnumerables are all batched transparently whenever it&#8217;s possible to do so.  No calling code had to be modified to get this benefit.  Queries that return single values (an entity instance or a scalar value) that still use the &#8216;old&#8217; FindOne, GetScalar and Count methods obviously couldn&#8217;t benefit from the transparent batching without breaking backwards compatibility, but the new methods that were introduced do enable transparent batching for these queries from now on.</p>
<p>Does all of this sound too good to be true? I&#8217;d be skeptic too if i were you but i made these changes a few months ago actually and we have been using this stuff on a couple of projects with zero problems.  </p>
<p>Obviously, you need NHibernate 2.1 Alpha 1 (or later) for this or the current trunk, both of which i would recommend over NH 2.0 at this point.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Performance Rules Of Thumb</title>
		<link>http://davybrion.com/blog/2009/02/performance-rules-of-thumb/</link>
		<comments>http://davybrion.com/blog/2009/02/performance-rules-of-thumb/#comments</comments>
		<pubDate>Sun, 15 Feb 2009 20:44:45 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=922</guid>
		<description><![CDATA[A lot of developers deal with performance differently. Some care too much, trying to optimize every single piece of code they write. Some care too little, not thinking about performance at all until it is proven to be a problem. I think both of these approaches suck and usually try to find a healthy balance [...]]]></description>
			<content:encoded><![CDATA[<p>A lot of developers deal with performance differently.  Some care too much, trying to optimize every single piece of code they write.  Some care too little, not thinking about performance at all until it is proven to be a problem.  I think both of these approaches suck and usually try to find a healthy balance between them.</p>
<p>Below is a list of rules of thumb that i always try to keep in mind.  Keep in mind that these are just rules of thumb&#8230; they are not rules that never should be broken, nor are they applicable to each and every situation.  In general though, i do believe that if you keep these in mind you can avoid serious performance issues and the need to do heavy architectural refactoring in the long run.  So without further ado, these are the performance-related things that i do care about while i&#8217;m writing my code:</p>
<ul>
<li><strong>Be careful with anything that goes out of process</strong> (web/wcf service calls, database calls, external systems/components, &#8230;).  The cost of these calls is often higher than you&#8217;d imagine and might not become noticeable until the load on your system increases, or when you start executing these calls in long loops.</li>
<li><strong>Fetch your data in a smart manner</strong>&#8230; Never retrieve data in a loop, but retrieve it outside of the loop in a more coarse-grained manner.  Sometimes it makes sense to use some joins to retrieve data, but in other cases you&#8217;re better off with executing separate queries to avoid retrieving large Cartesian products.  If your data layer implements caching in some way, use it in a smart manner</li>
<li><strong>Dispose objects that need it as soon as possible</strong>&#8230;  Not doing this could lead to costly dangling resources and/or memory leaks&#8230; if this eventually leads to swapping/paging you end up with abysmal performance</li>
<li><strong>Don&#8217;t transfer more data than you need to</strong>.  Whether you&#8217;re sending data over a service or you&#8217;re pushing HTML to a browser, your total bandwidth and/or the client&#8217;s download speed is usually limited so this could lead to slowdowns that you can often avoid.  Note that i don&#8217;t recommend making everything as compact as possible, but a little bit of common sense can go a long way here.</li>
<li><strong>Don&#8217;t go crazy with multi-threading and asynchronous operations</strong>.  While these can generally help a lot when it comes to responsiveness (and thus, the perceived &#8216;slowness&#8217; of your application) they aren&#8217;t always the perfect solution.  I once saw an &#8216;architect&#8217; run a data import process (which had to insert that data in a remote database) over 64 threads, because it was too slow in one thread.  He was surprised to see that his 64-thread solution wasn&#8217;t faster than his single-threaded version.  I wasn&#8217;t surprised at all&#8230; I suggested getting rid of the multi-threading and to batch the insert statements, which improved the situation greatly.</li>
<li><strong>Don&#8217;t hold on to large sets of data for too long</strong>.  A large set of data could be a lot of database records, but it could just as well be a lot of strings, or just other objects in general.  Keeping these in memory for a long time prevents them from being garbage collected as soon as they can be, which can greatly increase memory pressure in your system.  Be especially careful with long-running loops that iterate over large sets of data.  If you no longer need the data after you&#8217;ve left the loop, you&#8217;re often better off getting rid of each item in the set as you&#8217;re done processing it.</li>
</ul>
<p>And that&#8217;s pretty much it&#8230; outside of the stuff listed above, i typically don&#8217;t care about performance.  I try to keep my code clean and focused, and rely on profiling to identify performance hotspots.  When the profiler identifies problems, they are often more easy to solve if you&#8217;ve kept your code clean than it would be if you had tried to prematurely optimize in the wrong places.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/02/performance-rules-of-thumb/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Batching Remote Operations Is Not Premature Optimization</title>
		<link>http://davybrion.com/blog/2008/12/batching-remote-operations-is-not-premature-optimization/</link>
		<comments>http://davybrion.com/blog/2008/12/batching-remote-operations-is-not-premature-optimization/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 22:14:09 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=702</guid>
		<description><![CDATA[I spent a day at Devoxx (formerly known as Javapolis) this week, and one of the presentations i saw was about common performance anti-patterns, given by Alois Reitbauer from DynaTrace. While i didn&#8217;t really hear anything new during the presentation, i did kinda like how the speaker stressed that while premature optimization is indeed evil, [...]]]></description>
			<content:encoded><![CDATA[<p>I spent a day at <a href="http://www.devoxx.com/display/JV08/Home">Devoxx</a> (formerly known as Javapolis) this week, and one of the presentations i saw was about common performance anti-patterns, given by <a href="http://blog.dynatrace.com/author/alois-reitbauer/">Alois Reitbauer</a> from <a href="http://www.dynatrace.com/en/">DynaTrace</a>.  While i didn&#8217;t really hear anything new during the presentation, i did kinda like how the speaker stressed that while premature optimization is indeed evil, certain things simply don&#8217;t belong in that category and are things you should definitely keep an eye on throughout the development of your projects.</p>
<p>Those of you who&#8217;ve been reading this blog for a while know that i&#8217;ve often stressed the <a href="http://davybrion.com/blog/2008/06/the-query-batcher/">importance</a> <a href="http://davybrion.com/blog/2008/08/batching-sqlcommand-queries/">of</a> <a href="http://davybrion.com/blog/2008/06/batching-wcf-calls/">reducing</a> <a href="http://davybrion.com/blog/2008/07/batching/">the number</a> <a href="http://davybrion.com/blog/2008/09/the-select-command-batcher/">of</a> <a href="http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/">remote</a> <a href="http://davybrion.com/blog/2008/11/why-on-earth-would-a-developer-do-this/">calls</a>.  Yeah that&#8217;s right, i just linked to 7 of my own posts in a single sentence :p</p>
<p>Anyways, there were a few people who thought that my preference for batching queries/service calls was actually a case of premature optimization, and that it was therefor evil and not something you should be doing until it was actually necessary to do so.  The speaker of the presentation explained that there is a difference between premature optimization and pro-active performance management.  Performance and scalability simply do not come for free, and you have to keep certain things in mind if you want your system to have those qualities.  </p>
<p>Now, before i go further, i would like to state that i do believe that clean, simple and reusable code is something that developers should always strive for.   I also believe that you should try to limit the number of times you hit the database, or the number of remote service calls you make in a single business transaction.  Those goals often seem to contradict each other.  There aren&#8217;t too many data access layers that allow you to easily perform multiple queries in a single roundtrip while still making sure that each query is reusable in a different context.  It gets even worse when it comes to remote services.  As you undoubtedly know, a lot of industry experts will recommend that you provide coarse-grained service interfaces instead of fine-grained service interfaces.  The upside of coarse-grained interfaces is that they often offer better performance due to less chattiness in communication.  Unfortunately, it also often also leads to services that are <strong>implicitly</strong> coupled against the clients that are known to be using them.  With that i mean that many of those coarse-grained services are designed with certain client-characteristics in mind.  And shouldn&#8217;t services be independent of the clients that use them?  This approach typically has an impact on the reusability of those services for clients which are to be developed after the service has already been deployed. </p>
<p>So how do we solve these issues? It&#8217;s pretty simple.  I want each database query to be reusable in whatever way i need: combined with other queries in a single roundtrip, or executed separately.  I also want a fine-grained service interface where i can execute precisely the &#8216;remote action&#8217; i need, and avoid the chattiness when i need to execute several of those &#8216;remote actions&#8217; in a single business transaction.  The answer is of course: batching of remote operations, whether they are database queries or remote service calls or whatever else that essentially boils down to an out-of-process call.</p>
<p>I really think that every kind of architecture should at least make this reasonably easy to do so.  It really doesn&#8217;t take that much effort (or in some cases i&#8217;d even call it imagination) to make all of this possible. I&#8217;m actually pretty lazy so if i can manage to get it done, there&#8217;s no reason in the world why you shouldn&#8217;t.  It can be done pretty easily, and it really doesn&#8217;t come with that much of a cost.  Of course, writing your code this way takes a little bit more work than doing it the &#8216;easy way&#8217; (little more being &#8216;minutes&#8217; vs &#8216;hours&#8217; though).  But then again, if the &#8216;easy way&#8217; were the right way, we wouldn&#8217;t even be talking about performance anti-patterns, right?</p>
<p>For me personally, i&#8217;ve gotten to the point where i really couldn&#8217;t care less about possibly slow performing code in advance, as long as that code is executed in-process.  No matter how good you are, you will practically always guess wrong when it comes to slow-performing in-process code.  Just write clean and readable code and if some parts of it turn out to be slow, you just use a profiler and it will quickly tell you which parts are causing the slowdowns.  It&#8217;s pretty much always the last place you suspect so why bother writing difficult code for parts that probably weren&#8217;t going to be a problem anyway.   But for out-of-process stuff: be vigilant, because any performance problem related to it could have easily been avoided from the start. </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/12/batching-remote-operations-is-not-premature-optimization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Why On Earth Would A Developer Do This?</title>
		<link>http://davybrion.com/blog/2008/11/why-on-earth-would-a-developer-do-this/</link>
		<comments>http://davybrion.com/blog/2008/11/why-on-earth-would-a-developer-do-this/#comments</comments>
		<pubDate>Sat, 22 Nov 2008 14:59:19 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=607</guid>
		<description><![CDATA[I just saw the following piece of code: &#160;&#160;&#160; &#160;&#160;&#160; public void Execute() &#160;&#160;&#160; &#160;&#160;&#160; { &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; ArrayList empIds = PayrollDatabase.GetAllEmployeeIds(); &#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; foreach (int empId in empIds) &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; { &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; Employee employee = PayrollDatabase.GetEmployee(empId); &#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; if (employee.IsPayDate(payDate)) &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>I just saw the following piece of code:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Execute()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">ArrayList</span> empIds = <span style="color: #2b91af;">PayrollDatabase</span>.GetAllEmployeeIds();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: blue;">int</span> empId <span style="color: blue;">in</span> empIds)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Employee</span> employee = <span style="color: #2b91af;">PayrollDatabase</span>.GetEmployee(empId);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (employee.IsPayDate(payDate))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">DateTime</span> startDate = employee.GetPayPeriodStartDate(payDate);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Paycheck</span> pc = <span style="color: blue;">new</span> <span style="color: #2b91af;">Paycheck</span>(startDate, payDate);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; paychecks[empId] = pc;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; employee.Payday(pc);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The code is old, pre .NET 2.0.  But no, the usage of the ArrayList isn&#8217;t what bothers me here.  It first gets all of the Id values for all of the employees in the database.  Then it loops through the list of Id values, and fetches each employee from the database.  Whenever i see this kind of code, it makes me want to kick the person who wrote it.  </p>
<p>In case you don&#8217;t know what is so bad about this, think about this: if you have 5 employees you first send one select statement to the database to get their id values.  Then you send another 5 select statements to the database to get the data of each employee.  Oh well, 6 queries isn&#8217;t that big of a deal right? It sure as hell is if you could&#8217;ve just as easily gotten all of the required data with one query (and only one expensive roundtrip)!  Imagine you have to calculate the paychecks of 100 employees instead of 5.  How about 1000 employees? </p>
<p>What i really don&#8217;t understand about this is that this kind of code gets written <strong>every</strong> day.  Do these people simply don&#8217;t care or do they genuinely not know how bad this is?  If they don&#8217;t know, that&#8217;s truly sad.  If they don&#8217;t care, that&#8217;s even worse because a developer who knows how bad this is but still writes it, obviously takes no pride at all in his/her work and (IMO) has little respect for the code, the team, the company and the client.</p>
<p>In case you&#8217;re wondering where i saw this code&#8230; it&#8217;s in Robert C. Martin&#8217;s <a href="http://www.amazon.com/Principles-Patterns-Practices-Robert-Martin/dp/0131857258/ref=pd_bbs_sr_1?ie=UTF8&#038;s=books&#038;qid=1227365619&#038;sr=8-1">Agile Principles, Patterns, and Practices in C#</a> book.  Yes, <strong>the</strong> Robert C. Martin, aka Uncle Bob.  I probably shouldn&#8217;t criticize such a well known figure in the OO world, but seriously Bob, what were you smoking? The purpose of the whole book is to teach people how to write good code and there is tremendous amount of valuable information in there.  But putting code like this in your examples is really inexcusable.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/11/why-on-earth-would-a-developer-do-this/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Bulk Data Operations With NHibernate&#8217;s Stateless Sessions</title>
		<link>http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/</link>
		<comments>http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 19:28:15 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=543</guid>
		<description><![CDATA[In my previous post, i showed how you can configure NHibernate to batch create/update/delete statements and what kind of performance benefits you can get from it. In this post, we&#8217;re going to take this a bit further so we can actually use NHibernate in bulk data operations, an area where ORM&#8217;s traditionally perform pretty badly. [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous <a href="http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/">post</a>, i showed how you can configure NHibernate to batch create/update/delete statements and what kind of performance benefits you can get from it.  In this post, we&#8217;re going to take this a bit further so we can actually use NHibernate in bulk data operations, an area where ORM&#8217;s traditionally perform pretty badly.</p>
<p>First of all, let&#8217;s get back to our test code from the last post:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> testObjects = CreateTestObjects(500000);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> stopwatch = <span style="color: blue;">new</span> <span style="color: #2b91af;">Stopwatch</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Start();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">ITransaction</span> transaction = Session.BeginTransaction())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: blue;">var</span> testObject <span style="color: blue;">in</span> testObjects)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session.Save(testObject);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; transaction.Commit();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Stop();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> time = stopwatch.Elapsed;</p>
</div>
<p></code></p>
<p>The only thing that changed since the previous post is the amount of objects that are created. In the previous post we only created 10000 objects, whereas now we&#8217;ll be creating 500000 objects.</p>
<p>The batch size is configured like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">property</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">adonet.batch_size</span>&quot;<span style="color: blue;">&gt;</span>100<span style="color: blue;">&lt;/</span><span style="color: #a31515;">property</span><span style="color: blue;">&gt;</span></p>
</div>
<p></code></p>
<p>This means that NHibernate will send its DML statements in batches of 100 statements instead of sending all of them one by one.  The above code runs in 2 minutes and 24 seconds with a batch size of 100.  </p>
<p>However, if we use NHibernate&#8217;s IStatelessionSession instead of a regular ISession, we can get some nice improvements.  First of all, here&#8217;s the code to use the IStatelessSession:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> testObjects = CreateTestObjects(500000);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> stopwatch = <span style="color: blue;">new</span> <span style="color: #2b91af;">Stopwatch</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Start();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">IStatelessSession</span> statelessSession = sessionFactory.OpenStatelessSession())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">ITransaction</span> transaction = statelessSession.BeginTransaction())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: blue;">var</span> testObject <span style="color: blue;">in</span> testObjects)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; statelessSession.Insert(testObject);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; transaction.Commit();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Stop();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> time = stopwatch.Elapsed;</p>
</div>
<p></code></p>
<p>As you can see, apart from the usage of the IStatelessSession instead of the regular ISession, this is pretty much the same code.</p>
<p>With a batch-size of 100, this code creates and inserts the 500000 records in 1 minute and 26 seconds.  While not a spectacular improvement, it&#8217;s definitely a nice improvement in duration.</p>
<p>The biggest difference however is in memory usage while the code is running. A regular NHibernate ISession keeps a lot of data in its first-level cache (this enables a lot of the NHibernate magical goodies).  The IStatelessSession however, does no such thing.  It does no caching whatsoever and it also doesn&#8217;t fire all of the events that you could usually plug into.  This is strictly meant to be used for bulk data operations.</p>
<p>To give you an idea on the difference in memory usage, here are the memory statistics (captured by Process Explorer) after running the original code (with the ISession instance):</p>
<p><a href="http://davybrion.com/blog/wp-content/uploads/2008/10/isession.png"><img src="http://davybrion.com/blog/wp-content/uploads/2008/10/isession.png" alt="" title="isession" width="398" height="385" class="alignnone size-full wp-image-551" /></a></p>
<p>And here are the memory statistics after running the modified code (with the IStatelessSession instance):</p>
<p><a href="http://davybrion.com/blog/wp-content/uploads/2008/10/istatelesssession.png"><img src="http://davybrion.com/blog/wp-content/uploads/2008/10/istatelesssession.png" alt="" title="istatelesssession" width="400" height="386" class="alignnone size-full wp-image-552" /></a></p>
<p>Quite a difference for what is essentially the same operation.  We could even improve on this because the code in its current form keeps all of the object instances in its own collection, preventing them from being garbage collected after they have been inserted in the database.  But i think this already demonstrates the value in using the IStatelessSession if you need to perform bulk operations.</p>
<p>Obviously, this will never perform as well as a bulk data operation that directly uses low-level ADO.NET code.  But if you already have the NHibernate mappings and infrastructure set up, implementing those bulk operations could be cheaper while still being &#8216;fast enough&#8217; for most situations.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Batching NHibernate&#8217;s DML Statements</title>
		<link>http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/</link>
		<comments>http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 18:22:33 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=545</guid>
		<description><![CDATA[An oft-forgotten feature of NHibernate is that of batching DML statements. If you need to create, update or delete a bunch of objects you can get NHibernate to send those statements in batches instead of one by one. Let&#8217;s give this a closer look. I have an &#8216;entity&#8217; with the following mapping: &#160; &#60;class name=&#34;CrudTest&#34; [...]]]></description>
			<content:encoded><![CDATA[<p>An oft-forgotten feature of NHibernate is that of batching DML statements.  If you need to create, update or delete a bunch of objects you can get NHibernate to send those statements in batches instead of one by one.  Let&#8217;s give this a closer look.</p>
<p>I have an &#8216;entity&#8217; with the following mapping:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &lt;</span><span style="color: #a31515;">class</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">CrudTest</span>&quot;<span style="color: blue;"> </span><span style="color: red;">table</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">CrudTest</span>&quot;<span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">id</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">Id</span>&quot;<span style="color: blue;"> </span><span style="color: red;">column</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">Id</span>&quot;<span style="color: blue;"> </span><span style="color: red;">type</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">guid</span>&quot;<span style="color: blue;"> &gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span style="color: #a31515;">generator</span><span style="color: blue;"> </span><span style="color: red;">class</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">assigned</span>&quot;<span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;/</span><span style="color: #a31515;">id</span><span style="color: blue;">&gt;</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">property</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">Description</span>&quot;<span style="color: blue;"> </span><span style="color: red;">column</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">Description</span>&quot;<span style="color: blue;"> </span><span style="color: red;">type</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">string</span>&quot;<span style="color: blue;"> </span><span style="color: red;">length</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">200</span>&quot;<span style="color: blue;"> </span><span style="color: red;">not-null</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">true</span>&quot;<span style="color: blue;"> /&gt;</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &lt;/</span><span style="color: #a31515;">class</span><span style="color: blue;">&gt;</span></p>
</div>
<p></code></p>
<p>Nothing special here, just a Guid Id field and a string Description field. </p>
<p>First, let&#8217;s see how much time it takes to create 10000 records of this without using the batching feature.  I use the following method to create a bunch of dummy objects:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">CrudTest</span>&gt; CreateTestObjects(<span style="color: blue;">int</span> count)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">CrudTest</span>&gt; objects = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">CrudTest</span>&gt;(count);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">for</span> (<span style="color: blue;">int</span> i = 0; i &lt; count; i++)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; objects.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">CrudTest</span> { Id = <span style="color: #2b91af;">Guid</span>.NewGuid(), Description = <span style="color: #2b91af;">Guid</span>.NewGuid().ToString() });</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> objects;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Then, the code to persist these objects:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> testObjects = CreateTestObjects(10000);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> stopwatch = <span style="color: blue;">new</span> <span style="color: #2b91af;">Stopwatch</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Start();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: #2b91af;">ITransaction</span> transaction = Session.BeginTransaction())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: blue;">var</span> testObject <span style="color: blue;">in</span> testObjects)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session.Save(testObject);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; transaction.Commit();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; stopwatch.Stop();</p>
</div>
<p></code></p>
<p>Without enabling the batching, this code took 23 seconds to run on my cheap MacBook.  Now let&#8217;s enable the batching in the hibernate.cfg.xml file:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">property</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">adonet.batch_size</span>&quot;<span style="color: blue;">&gt;</span>5<span style="color: blue;">&lt;/</span><span style="color: #a31515;">property</span><span style="color: blue;">&gt;</span></p>
</div>
<p></code></p>
<p>A batch size of 5 is still very small, but for this test it means that it only has to do 2000 trips to the database instead of the original 10000.  The code above now runs in 5.5 seconds.  Setting the batch size to 100 made it run in 1.8 seconds.  Going from 23 to 1.8 seconds with a small configuration change is a pretty nice improvement with very little effort.  Obviously, these aren&#8217;t real benchmarks so your results may vary but i think it does show that you can easily get some performance benefits from it.</p>
<p>You can get performance benefits like this whenever you need to create/update/delete a bunch of records simply by enabling this setting.  Keep in mind that this batching of statements doesn&#8217;t apply to select queries&#8230; for that you need to use NHibernate&#8217;s MultiCriteria or MultiQuery features <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Another thing to keep in mind is that for this test i used the &#8216;assigned&#8217; Id generator&#8230; which means that the developer is responsible for providing the Id value for new objects.  One of the consequences of this is that NHibernate does not have to go to the database to retrieve the Id values like it would have to do if you were using (for instance) Identity Id values.  If you were using the Identity Id generator, this configuration setting would have no effect whatsoever for inserts, although the benefits would still apply to update and delete statements.</p>
<p>Note that this approach is good for regular applications, but it&#8217;s still not good enough if you need to process very large data sets (like import processes and things of that nature). Obviously, an ORM isn&#8217;t well suited for those purposes, but we will examine another NHibernate feature in a future post which makes it possible to use NHibernate in such bulk operations with a pretty low performance overhead.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>The Select Command Batcher</title>
		<link>http://davybrion.com/blog/2008/09/the-select-command-batcher/</link>
		<comments>http://davybrion.com/blog/2008/09/the-select-command-batcher/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 10:30:25 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=388</guid>
		<description><![CDATA[As promised, this post describes a way to make batching of select queries through SqlCommands as easy to use as my QueryBatcher for NHibernate. So naturally, i came up with the SelectCommandBatcher class (i know, i really need to come up with better names). It&#8217;s very similar in usage to the QueryBatcher for NHibernate. Obviously, [...]]]></description>
			<content:encoded><![CDATA[<p>As <a href="http://davybrion.com/blog/2008/08/batching-sqlcommand-queries/">promised</a>, this post describes a way to make batching of select queries through SqlCommands as easy to use as my <a href="http://davybrion.com/blog/2008/06/the-query-batcher/">QueryBatcher for NHibernate</a>.  </p>
<p>So naturally, i came up with the SelectCommandBatcher class (i know, i really need to come up with better names).  It&#8217;s very similar in usage to the QueryBatcher for NHibernate.  Obviously, there is one important difference: NHibernate takes care of transforming the database result into entity objects automagically.  For the SelectCommandBatcher, you either have to provide some functionality that takes care of mapping the database results to objects, or you can access the results through DataTables (yikes!).</p>
<p>Let&#8217;s just get straight to the code, shall we? For the first couple of examples, i&#8217;ll focus specifically on how you can retrieve your results so each example only uses one command.  At the end of the examples, there is of course one example that illustrates how you can add multiple SqlCommands and fetch the results in one roundtrip (which is after all the purpose of the SelectCommandBatcher class).</p>
<p>Suppose you have some code that is able to transform the content of a DataTable (or a DataRow) to a List of entities (or one entity):</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">Product</span>&gt; TransformTableToListOfProducts(<span style="color: #2b91af;">DataTable</span> table)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> products = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">Product</span>&gt;();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: #2b91af;">DataRow</span> row <span style="color: blue;">in</span> table.Rows)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; products.Add(TransformRowToProduct(row));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> products;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">Product</span> TransformRowToProduct(<span style="color: #2b91af;">DataRow</span> row)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// normally you'd put the values of the row in the product entity</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">Product</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Obviously, this simply returns a new Product for each DataRow in the DataTable.  If this were real code, you&#8217;d have to put the data of the DataRow into the Product instance.  Feel free to consider me lazy <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>With the SelectCommandBatcher, you can now do this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"products"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT * FROM dbo.Products"</span>));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">Product</span>&gt; results = </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.GetEnumerableResult&lt;<span style="color: #2b91af;">Product</span>&gt;(<span style="color: #a31515;">"products"</span>, TransformTableToListOfProducts);</p>
</div>
<p></code></p>
<p>Notice how the TransformTableToListOfProducts method is passed to the GetEnumerableResult method as a parameter.  How does it work? It&#8217;s pretty simple really: The GetEnumerableResult method&#8217;s definition looks like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IEnumerable</span>&lt;T&gt; GetEnumerableResult&lt;T&gt;(<span style="color: blue;">string</span> key, </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">DataTable</span>, <span style="color: #2b91af;">IEnumerable</span>&lt;T&gt;&gt; transformTableToListOfEntitiesMethod);</p>
</div>
<p></code></p>
<p>Basically, this method requires you to provide a delegate which accepts a DataTable as its sole incoming parameter, and returns an IEnumerable of T with T being any Type your code transforms the result to. </p>
<p>What if your Data Access Layer only has methods to transform individual rows to entities? No problem:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"products"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT * FROM dbo.Products"</span>));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">Product</span>&gt; results = commandBatcher.GetEnumerableResult&lt;<span style="color: #2b91af;">Product</span>&gt;(<span style="color: #a31515;">"products"</span>, TransformRowToProduct);</p>
</div>
<p></code></p>
<p>This code uses an overload of the GetEnumerableResult method that looks like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IEnumerable</span>&lt;T&gt; GetEnumerableResult&lt;T&gt;(<span style="color: blue;">string</span> key, </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">DataRow</span>, T&gt; transformRowToEntityMethod);</p>
</div>
<p></code></p>
<p>You just need to pass a delegate which takes a DataRow as its sole incoming parameter, and returns an instance of T with T being any Type your code transforms the result to.  The delegate that gets passed in will be called for every DataRow in the DataTable which contains the results of that specific select command.</p>
<p>Or if your query only returns a single row, you can do this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"firstProduct"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT TOP 1 * FROM dbo.Products"</span>));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Product</span> product = commandBatcher.GetSingleResult&lt;<span style="color: #2b91af;">Product</span>&gt;(<span style="color: #a31515;">"firstProduct"</span>, TransformRowToProduct);</p>
</div>
<p></code></p>
<p>Scalar values you say? How about this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"productCount"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT COUNT(*) FROM dbo.Products"</span>));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">int</span> count = commandBatcher.GetSingleResult&lt;<span style="color: blue;">int</span>&gt;(<span style="color: #a31515;">"productCount"</span>);</p>
</div>
<p></code></p>
<p>Or if you&#8217;re old-school (sorry, couldn&#8217;t resist) and just want the DataTable, you can use this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"products"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT * FROM dbo.Products"</span>));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">DataTable</span> table = commandBatcher.GetResultAsDataTable(<span style="color: #a31515;">"products"</span>);</p>
</div>
<p></code></p>
<p>And of course, here&#8217;s how you can execute multiple select queries in one roundtrip:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"products"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT * FROM dbo.Products"</span>));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.AddCommand(<span style="color: #a31515;">"supplier"</span>, <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>(<span style="color: #a31515;">"SELECT * FROM dbo.Suppliers"</span>));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">Product</span>&gt; products = </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.GetEnumerableResult&lt;<span style="color: #2b91af;">Product</span>&gt;(<span style="color: #a31515;">"products"</span>, TransformRowToProduct);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">Supplier</span>&gt; suppliers = </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandBatcher.GetEnumerableResult&lt;<span style="color: #2b91af;">Supplier</span>&gt;(<span style="color: #a31515;">"supplier"</span>, TransformRowToSupplier);</p>
</div>
<p></code></p>
<p>The queries are executed as soon as you try to retrieve the first result.</p>
<p>That&#8217;s all pretty easy to use right? So how does it work? Here&#8217;s the code:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">SelectCommandBatcher</span> : <span style="color: #2b91af;">Disposable</span>, <span style="color: #2b91af;">ISelectCommandBatcher</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">SqlConnection</span> sqlConnection;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">Dictionary</span>&lt;<span style="color: blue;">string</span>, <span style="color: blue;">int</span>&gt; queryResultPositions;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt; commandList;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: #2b91af;">DataSet</span> results;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> SelectCommandBatcher(<span style="color: #2b91af;">SqlConnection</span> sqlConnection)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">this</span>.sqlConnection = sqlConnection;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; queryResultPositions = <span style="color: blue;">new</span> <span style="color: #2b91af;">Dictionary</span>&lt;<span style="color: blue;">string</span>, <span style="color: blue;">int</span>&gt;();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandList = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt;();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> DisposeManagedResources()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (results != <span style="color: blue;">null</span>) results.Dispose();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// don't dispose the connection, we didn't create it...</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> AddCommand(<span style="color: blue;">string</span> key, <span style="color: #2b91af;">SqlCommand</span> command)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commandList.Add(command);&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; queryResultPositions.Add(key, commandList.Count - 1);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">IEnumerable</span>&lt;T&gt; GetEnumerableResult&lt;T&gt;(<span style="color: blue;">string</span> key, </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">DataTable</span>, <span style="color: #2b91af;">IEnumerable</span>&lt;T&gt;&gt; transformTableToListOfEntitiesMethod)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ExecuteQueriesIfNecessary();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> transformTableToListOfEntitiesMethod(GetResultTable(key));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">IEnumerable</span>&lt;T&gt; GetEnumerableResult&lt;T&gt;(<span style="color: blue;">string</span> key, </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">DataRow</span>, T&gt; transformRowToEntityMethod)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ExecuteQueriesIfNecessary();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> GetEnumerableResult(key, table =&gt;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> resultList = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;T&gt;();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: #2b91af;">DataRow</span> row <span style="color: blue;">in</span> table.Rows)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; resultList.Add(transformRowToEntityMethod(row));</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> resultList;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; });</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> T GetSingleResult&lt;T&gt;(<span style="color: blue;">string</span> key)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ExecuteQueriesIfNecessary();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> (T)GetResultTable(key).Rows[0].ItemArray[0];</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> T GetSingleResult&lt;T&gt;(<span style="color: blue;">string</span> key, <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">DataRow</span>, T&gt; transformRowToEntityMethod)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ExecuteQueriesIfNecessary();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> resultTable = GetResultTable(key);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (resultTable.Rows.Count &gt; 0)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> transformRowToEntityMethod(resultTable.Rows[0]);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">else</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> <span style="color: blue;">default</span>(T);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DataTable</span> GetResultAsDataTable(<span style="color: blue;">string</span> key)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ExecuteQueriesIfNecessary();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> GetResultTable(key);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">void</span> ExecuteQueriesIfNecessary()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (results == <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> combinedCommand = <span style="color: blue;">new</span> <span style="color: #2b91af;">SelectCommandCombiner</span>(commandList).CreateCombinedCommand();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; combinedCommand.Connection = sqlConnection;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> adapter = <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlDataAdapter</span>(combinedCommand))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; results = <span style="color: blue;">new</span> <span style="color: #2b91af;">DataSet</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; adapter.Fill(results);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: #2b91af;">DataTable</span> GetResultTable(<span style="color: blue;">string</span> key)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> results.Tables[queryResultPositions[key]];</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>I&#8217;ve also added it to my <a href="http://davybrion.com/blog/stuff/">Library</a>, although not yet in the downloadable file.  You can find the code in the <a href="http://davybrion.com/publicsvn/Brion.Library/Brion.Library.ServerSide/AdoNet/SelectCommandBatcher.cs">svn repo</a> though.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/09/the-select-command-batcher/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Batching SqlCommand Queries</title>
		<link>http://davybrion.com/blog/2008/08/batching-sqlcommand-queries/</link>
		<comments>http://davybrion.com/blog/2008/08/batching-sqlcommand-queries/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 18:00:56 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=372</guid>
		<description><![CDATA[As you know, i always like to reduce unnecessary roundtrips. With my Request/Response service layer and my QueryBatcher for NHibernate, it&#8217;s trivially easy to do so. But what if you&#8217;re in a situation where you can&#8217;t use NHibernate and are stuck with low-level SqlCommands? It&#8217;s actually not hard to enable batching those (select) queries either. [...]]]></description>
			<content:encoded><![CDATA[<p>As you know, i always like to reduce <a href="http://davybrion.com/blog/2008/07/batching/">unnecessary roundtrips</a>.  With my <a href="http://davybrion.com/blog/2008/07/the-request-response-service-layer/">Request/Response service layer</a> and my <a href="http://davybrion.com/blog/2008/06/the-query-batcher/">QueryBatcher for NHibernate</a>, it&#8217;s trivially easy to do so. But what if you&#8217;re in a situation where you can&#8217;t use NHibernate and are stuck with low-level SqlCommands? It&#8217;s actually not hard to enable batching those (select) queries either.  (note: for insert/update/delete Commands, there is <a href="http://www.ayende.com/Blog/archive/2006/09/14/7275.aspx">a better way</a>).</p>
<p>People with a lot of straight-up ADO.NET experience probably already know this, but you can simply combine your select statements into one SqlCommand.  When you execute that command, you get the results to each of the queries that was in the command.  So far, nothing new here.  I&#8217;m currently using a Data Access Layer at work which creates SqlCommand objects for select queries that you can build up through an API.  Obviously, i&#8217;d like a way to use each query in whatever way is best for the specific scenario i&#8217;m working on.  I basically want to be able to execute the SqlCommand objects as a stand-alone query, or in a batch with other queries, without having to modify the code that creates the SqlCommand objects.  </p>
<p>So i wrote a SelectCommandCombiner class which allows you to combine multiple SqlCommands into one SqlCommand, while making sure that none of the parameters conflict with each other.  Here&#8217;s the code:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">SelectCommandCombiner</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt; commands = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt;();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> SelectCommandCombiner() : <span style="color: blue;">this</span>(<span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>[0]) { }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> SelectCommandCombiner(<span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt; commandsToCombine)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commands = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt;();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (commandsToCombine != <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; AddCommands(commandsToCombine);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> AddCommands(<span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">SqlCommand</span>&gt; commandsToAdd)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; commands.AddRange(commandsToAdd);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">SqlCommand</span> CreateCombinedCommand()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> combinedCommand = <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlCommand</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> combinedCommandText = <span style="color: blue;">new</span> <span style="color: #2b91af;">StringBuilder</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> queryIndex = 0;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: blue;">var</span> currentCommand <span style="color: blue;">in</span> commands)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> currentCommandText = <span style="color: blue;">new</span> <span style="color: #2b91af;">StringBuilder</span>(currentCommand.CommandText);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CreateUniqueParameters(currentCommand, currentCommandText, combinedCommand, queryIndex);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; combinedCommandText.Append(currentCommandText + <span style="color: #a31515;">";"</span> + System.<span style="color: #2b91af;">Environment</span>.NewLine);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; queryIndex++;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; combinedCommand.CommandText = combinedCommandText.ToString();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> combinedCommand;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> CreateUniqueParameters(<span style="color: #2b91af;">SqlCommand</span> currentCommand, <span style="color: #2b91af;">StringBuilder</span> currentCommandText, </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">SqlCommand</span> combinedCommand, <span style="color: blue;">int</span> queryIndex)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: #2b91af;">SqlParameter</span> parameter <span style="color: blue;">in</span> currentCommand.Parameters)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> clonedParameter = CloneParameter(parameter);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; MakeParameterNameUnique(queryIndex, clonedParameter);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; combinedCommand.Parameters.Add(clonedParameter);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ReplaceOldNameWithNewName(parameter, clonedParameter, currentCommandText);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">SqlParameter</span> CloneParameter(<span style="color: #2b91af;">ICloneable</span> parameter)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> (<span style="color: #2b91af;">SqlParameter</span>)parameter.Clone();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> MakeParameterNameUnique(<span style="color: blue;">int</span> queryIndex, <span style="color: #2b91af;">SqlParameter</span> clonedParameter)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> modifiedParameterName = queryIndex + <span style="color: #a31515;">"_"</span> + clonedParameter.ParameterName;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; clonedParameter.ParameterName = modifiedParameterName;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> ReplaceOldNameWithNewName(<span style="color: #2b91af;">SqlParameter</span> parameter, <span style="color: #2b91af;">SqlParameter</span> clonedParameter, </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">StringBuilder</span> currentCommandText)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; currentCommandText.Replace(<span style="color: #a31515;">"@"</span> + parameter.ParameterName, <span style="color: #a31515;">"@"</span> + clonedParameter.ParameterName);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Now execute the command returned from the CreateCombinedCommand method and you&#8217;ll get all of the results in one roundtrip. There are a couple of ways to deal with the results&#8230; you could simply use a DataReader to loop through all the rows of all the result sets:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> reader = combinedCommand.ExecuteReader();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">do</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">while</span> (reader.Read())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// do something with the values in the current row</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; } </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">while</span> (reader.NextResult()); <span style="color: green;">// this moves to the next result set</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; reader.Close();</p>
</div>
<p></code></p>
<p>Or you could use a SqlDataAdapter to fill a DataSet:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> adapter = <span style="color: blue;">new</span> <span style="color: #2b91af;">SqlDataAdapter</span>(combinedCommand);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> dataSet = <span style="color: blue;">new</span> <span style="color: #2b91af;">DataSet</span>();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; adapter.Fill(dataSet);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: #2b91af;">DataTable</span> table <span style="color: blue;">in</span> dataSet.Tables)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">foreach</span> (<span style="color: #2b91af;">DataRow</span> row <span style="color: blue;">in</span> table.Rows)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// do something with the values</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>In a future post, i&#8217;ll try to make this as easy to use as the <a href="http://davybrion.com/blog/2008/06/the-query-batcher/">QueryBatcher for NHibernate</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/08/batching-sqlcommand-queries/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>.NET Memory Management</title>
		<link>http://davybrion.com/blog/2008/08/net-memory-management/</link>
		<comments>http://davybrion.com/blog/2008/08/net-memory-management/#comments</comments>
		<pubDate>Sat, 16 Aug 2008 18:44:32 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=311</guid>
		<description><![CDATA[Introduction Garbage Collection sure is great, isn&#8217;t it? We don&#8217;t have to keep track of all the memory we&#8217;ve allocated and we don&#8217;t need to release that memory when it&#8217;s no longer needed. Because that is after all what the Garbage Collector does for us, without us having to worry about it. This is actually [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Garbage Collection sure is great, isn&#8217;t it? We don&#8217;t have to keep track of all the memory we&#8217;ve allocated and we don&#8217;t need to release that memory when it&#8217;s no longer needed. Because that is after all what the Garbage Collector does for us, without us having to worry about it.  This is actually a widespread misconception among many .NET developers.  It&#8217;s true that Garbage Collection makes memory management a lot easier, but we simply can&#8217;t rely on it all the time. There are most certainly some things you must always keep in mind when it comes to memory management in .NET.</p>
<h2>Different Kinds Of Resources, Different Consequences</h2>
<p>In most pieces of code, you use variables. A lot of these variables are references to objects. When your variables go out of scope, they no longer exist.  When those variables are references to objects, only your reference is gone and the actual object that was referred to is still in memory somewhere. The Garbage Collector (GC) makes sure that orphaned objects (objects that no longer have a usable reference to them) are removed from memory. This is an automatic process within the .NET runtime.  Essentially, the GC periodically performs some checks on objects and if it comes to the conclusion that certain objects are no longer needed, it will remove them from memory.  This is a gross oversimplification of how it really works, but that is what it comes down to and that is also how most people think about the GC.</p>
<p>The GC in .NET is very smart and will almost always do a better job of memory management than you will. But there is one huge downside to it: the GC runs periodically and you have no deterministic way of knowing when it will run.  Sure, you can instruct the GC to perform a collection but in most cases that will actually have a negative impact on the memory management of your application.  I won&#8217;t go into the details here, but i will provide a follow-up post on this later on. For now, keep in mind that forcing a garbage collection to occur is really something you should avoid.</p>
<p>So is it really a problem that you don&#8217;t know for certain when the GC will run? It depends on which kind of objects that need to be removed from memory.  There are basically 2 kinds: managed and unmanaged resources. Managed resources are typical .NET types. Unmanaged resources (also referred to as Native Resources) are things that fall outside of the scope of the .NET managed environment.  These are usually things that are available within the Operating System, or that are available through lower-level development API&#8217;s (such as the Win32 API for instance).  Unmanaged resources can&#8217;t be cleaned up automatically by the .NET runtime, so if you use them directly, you are responsible for cleaning up after you&#8217;ve used them. Luckily, a lot of managed types are available that take care of the dirty details for you.  For instance, if you need to use a file in .NET, you&#8217;ll typically use a FileStream instance or something else that easily makes the content of the file available to you, or that easily allows you to write content to a file.  The FileStream is a managed type, but it uses unmanaged resources to implement the functionality it offers.  </p>
<p>Now think about this: you are using a managed type, so you shouldn&#8217;t need to perform any cleanup, right?  However, if that managed type uses unmanaged resources then they still need to be cleaned up. And those unmanaged resources should be cleaned up as soon as possible because they can be quite expensive.  These types usually offer a way to clean up the unmanaged resources they use in a deterministic manner.  They usually implement the IDisposable interface, which exposes a Dispose method.  When you call the Dispose method, the unmanaged resources are cleaned up right then and there and then there&#8217;s no need to wait for the garbage collector, which again, could be quite expensive when you (either directly or indirectly) have a bunch of unmanaged resources in memory that are waiting to be cleaned up.  </p>
<h2>Disposable Managed Resources</h2>
<p>I call types that implement the IDisposable interface Disposable Managed Resources. They are indeed managed types and thus they are guaranteed to be cleaned up when the GC comes around and notices that instances of these types are no longer needed.  However, if you merely trust on the GC to clean up instances of these types you are taking quite a risk. Any expensive resource it may hold might be cleaned up a lot later than it could have been.  Which can be very inefficient, and thus, quite costly.  </p>
<p>If a type implements the IDisposable interface, it usually has a good reason for doing so (there are of course exceptions to the rule). It is essentially a way of telling consumers of the type that it offers a deterministic way of cleaning up the resources it consumes and i believe you should take advantage of that.  If you don&#8217;t, you may end up with inefficient memory management, and that&#8217;s when people start complaining that Garbage Collection is &#8216;evil&#8217; or that it &#8216;sucks&#8217;. In most cases, people who feel that way simply don&#8217;t know how to use it properly.  The IDisposable interface and the Dispose Pattern (which we&#8217;ll get to in a minute) allow you to avoid most of the issues that are generally attributed to the Garbage Collection in general.</p>
<p>So how do we deal with this? First of all, if a type uses unmanaged resources, it should implement the IDisposable interface using the Dispose Pattern. Secondly, if any of your types use other types that implement IDisposable, it is your responsibility to make sure these types are properly disposed of.  You either dispose them when you no longer need them, or you must implement IDisposable and the Dispose Pattern yourself to make sure the Disposable Managed Resources you depend on are indeed properly disposed of.  If you need to implement IDisposable, your type effectively becomes a Disposable Managed Resource itself.  A lot of people think that this isn&#8217;t necessary, but by not doing so they are breaking the contract that the IDisposable interface implies. If a type implements IDisposable then either that type or any other type it may use probably uses unmanaged resources somewhere and you want to see these get cleaned up as soon as possible.  Because of that, i believe it&#8217;s best to implement IDisposable yourself if you&#8217;re holding any reference to a type that also implements it.</p>
<h2>The Dispose Pattern</h2>
<p>Implementing the IDisposable interface can be as easy as merely providing a public Dispose method where you perform your cleanup.  That&#8217;s really not a good way of doing it though, as it could lead to a bunch of other problems which might actually make the situation worse.  The best way to implement the IDisposable interface is to implement the Dispose Pattern, which looks like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyDisposableClass</span> : <span style="color: #2b91af;">IDisposable</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">bool</span> disposed = <span style="color: blue;">false</span>;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Dispose()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dispose(<span style="color: blue;">true</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// prevent this object from being placed in the finalization queue if some</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// derived class provides a finalizer</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">GC</span>.SuppressFinalize(<span style="color: blue;">this</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> Dispose(<span style="color: blue;">bool</span> disposing)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (!disposed)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">if</span> (disposing)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// dispose all Disposable Managed Resources here</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// dispose all Unmanaged Resources here</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// set disposed to true to prevent the code above from being</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// executed a second time</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; disposed = <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>If you don&#8217;t need a finalizer it&#8217;s best not to provide one (we&#8217;ll discuss finalizers later on).  If you do need one, you would implement it like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> ~MyDisposableClass()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Dispose(<span style="color: blue;">false</span>);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>So what&#8217;s so good about the Dispose pattern? Well, we make a clear distinction between what should happen when the object is disposed through the Dispose method, or when it&#8217;s being cleaned up by the finalizer. When the clean up occurs through a call to Dispose, it calls the protected virtual Dispose method with the disposing parameter set to true. When this parameter is true, you should call the Dispose method of each Disposable Managed Resource you&#8217;re holding a reference to. Outside of the if-statement, you should clean up each unmanaged resource you may be holding.</p>
<p>If your class (or a derived class) implements a finalizer method, it should call the Dispose method with the disposing parameter set to false.  The reason for this is that the order in which objects are finalized is not specified. If you&#8217;re not careful, you could accidentally call the Dispose method of a Disposable Managed Resource which may have already been finalized as well.  This would cause an exception and a finalizer method should never ever throw an exception because that could keep other objects from being finalized.</p>
<p>If you can, try to put this pattern into a reusable base class and make your Disposable Managed Resource holding types inherit from this.  An example of this approach can be found <a href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/">here</a>.</p>
<h2>Using Disposable Managed Resources</h2>
<p>In a lot of cases, you will use a Disposable Managed Resource within the scope of one method. In that case, you certainly don&#8217;t need to implement IDisposable. There are two things to keep in mind though. If you receive the Disposable Managed Resource as a method parameter, you are not responsible for disposing it! Somebody else created it, let them take care of the disposal. Things will most likely go wrong if you dispose objects that have been giving to you by somebody else. So in this case, you would just use the object and not worry about it any further:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoSomethingInteresting(<span style="color: #2b91af;">MyDisposableClass</span> disposableResource)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; disposableResource.DoWhateverItIsThatMakesYouSoSpecial();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// we reach the end of the method and we haven't Disposed the</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// Disposable Managed Resource because it wasn't our responsibility</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>However, if you create the object yourself, then you are responsible for getting rid of it properly. In that case, use a using block to make sure the object is disposed of even in case of unhandled exceptions:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoSomethingInteresting()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> myDisposableResource = <span style="color: blue;">new</span> <span style="color: #2b91af;">MyDisposableClass</span>())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; myDisposableResource.DoWhateverItIsThatMakesYouSoSpecial();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// ... some code could go here</span></p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// we reach the end of the method and we properly Disposed the</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// Disposable Managed Resource because it was our responsibility</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>In case you don&#8217;t know, the using-block guarantees that the Dispose method will be called when we leave the scope of the block.  It can get pretty tricky sometimes if you&#8217;re passing the Disposable Managed Resources to other objects that will hold a reference to them which will remain in use after you&#8217;ve left the using block. In this scenario, it&#8217;s possible that the object you&#8217;ve passed the Disposable Managed Resource to will try to invoke methods on the disposed instance. Also a situation you most certainly want to avoid because it will either cause unexpected behavior or even unhandled exceptions. The unhandled exceptions are easy to figure out, but the unexpected behavior might be difficult to debug.  The key in this scenario, is to figure out a way to not call Dispose on the resource until the other object is done with it.  Sometimes it might be enough to put your using block on a slightly higher level, other times you&#8217;ll have to keep a reference to the resource yourself, which effectively means you&#8217;ve now become an owner of the Disposable Managed Resource.</p>
<h2>Owning Disposable Managed Resources</h2>
<p>If you need to hold a reference to a Disposable Managed Resource, you are either the owner of the object or at least someone who owns a stake in the lifetime of the object.  If you are the owner, and you do not pass the Disposable Managed Resource to any other object then the solution is easy: implement IDisposable.  If you do pass the Disposable Managed Resource to other objects, then it can get tricky. Will they only use it to perform some action or will they hold a reference to it?  If they hold a reference to it, it means that they too have a stake in the lifetime of the resource.  Depending on the implementation of the other types, they may or may not call the Dispose method of the instance you created. Which could cause unexpected behavior or exceptions in your code. Make sure you are prepared for that if you&#8217;re passing these objects around. But you should definitely dispose of them in your own Dispose method.</p>
<p>If you didn&#8217;t create the Disposable Managed Resource, but you do need to hold a reference to it, then you&#8217;ve got some questions to answer. Does the type which provided you with the instance expect you to be solely responsible for the lifetime of the object? In case of factory classes or factory methods, the answer is usually &#8216;yes&#8217;.  If you&#8217;ve been given the instance by something that will probably make use of that same instance, i think it&#8217;s better not to dispose it.  Some people will probably disagree, but i don&#8217;t think it&#8217;s my responsibility to dispose objects that i didn&#8217;t create, unless the instance was given to me by a factory class or a factory method.  I would expect that the real owner of the resource would dispose of it. Still, it&#8217;s a difficult call to make.</p>
<h2>Finalizers</h2>
<p>Finally, i&#8217;d like to add a few words about Finalizers in .NET.  A finalizer is similar to a destructor in C++, in that it is the code that is run when your object is being removed from memory. The big difference is that you never know for sure when it will be run, which is why the IDisposable interface and the Dispose pattern was created. There are a lot of misconceptions going around about finalizers, so keep the following comments in mind. </p>
<p>First of all, finalizers only make sense when you have direct references to unmanaged resources. If you have unmanaged resources, implement IDisposable and provide a finalizer that calls the Dispose overload with the disposing parameter set to false. This should really be the only code inside your finalizer method. </p>
<p>Finalizers also come with a performance penalty. When finalizable objects are created, pointers to these objects are added to the finalization queue of the GC.  These finalizable objects are collected less frequently because the GC performs finalizations through its finalization queue. This finalization process is not executed as frequently as regular garbage collections because it&#8217;s quite costly. So not only are finalizable objects cleaned up less frequently, it takes more processing power to do so.  So if you have a lot of finalizable instances, your code&#8217;s performance can easily be impacted because of this.  </p>
<h2>Conclusion</h2>
<p>I hope i made it clear that there is a lot more to automatic memory management in .NET than simply relying on the GC to take care of all of the details for you. There is a lot more stuff that i didn&#8217;t cover in this post (it&#8217;s long enough already) but most .NET developers will probably get by pretty well with the advice given in this post.  It&#8217;s not an easy subject to explain so i hope everything was clear <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/08/net-memory-management/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Batching++</title>
		<link>http://davybrion.com/blog/2008/07/batching/</link>
		<comments>http://davybrion.com/blog/2008/07/batching/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 19:25:36 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=244</guid>
		<description><![CDATA[The usual example: &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; dispatcher.Add(new GetProductCategoriesRequest(), new GetSuppliersRequest()); &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; View.ProductCategories = dispatcher.Get&#60;GetProductCategoriesResponse&#62;().ProductCategories; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; View.Suppliers = dispatcher.Get&#60;GetSuppliersResponse&#62;().Suppliers; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; View.DataBind(); Thanks to my request/response service layer, those are two service requests that will be performed in one service call. On the server side, these two [...]]]></description>
			<content:encoded><![CDATA[<p>The usual example:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dispatcher.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">GetProductCategoriesRequest</span>(), <span style="color: blue;">new</span> <span style="color: #2b91af;">GetSuppliersRequest</span>());</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; View.ProductCategories = dispatcher.Get&lt;<span style="color: #2b91af;">GetProductCategoriesResponse</span>&gt;().ProductCategories;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; View.Suppliers = dispatcher.Get&lt;<span style="color: #2b91af;">GetSuppliersResponse</span>&gt;().Suppliers;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; View.DataBind();</p>
</div>
<p></code></p>
<p>Thanks to my <a href="http://davybrion.com/blog/2008/07/the-request-response-service-layer/">request/response service layer</a>, those are two service requests that will be performed in one service call.  On the server side, these two requests are dealt with separately.  But they merely retrieve data from the database.  Wouldn&#8217;t it be cool if those 2 queries were performed in one database roundtrip instead of two?  Wouldn&#8217;t it be cool if we could batch the queries that will be performed by read-only service requests into a single database roundtrip? It sure as hell would be. Implementing this was one of those irresistible challenges you just can&#8217;t say no to, so from now on we can actually do this.  I&#8217;m not gonna get into the actual implementation of how I got it working (check the code in the library for that if you&#8217;re interested), but i will show you how you can do this in your application.</p>
<p>First of all, if you have requests that merely return data, inherit from ReadOnlyRequest instead of the usual Request type:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Serializable</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">GetProductCategoriesRequest</span> : <span style="color: #2b91af;">ReadOnlyRequest</span> {}</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Serializable</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">GetSuppliersRequest</span> : <span style="color: #2b91af;">ReadOnlyRequest</span> {}</p>
</div>
<p></code></p>
<p>The handlers for these requests should inherit from the ReadOnlyRequestHandler base class instead of the usual RequestHandler class.  Btw, my ReadOnlyRequestHandler class inherits from my UoWRequestHandler class, which requires a IUnitOfWork instance to be passed to the constructor.  So we need to put an IUnitOfWork parameter into the constructor along with our other dependencies if we want the IOC container (or the request processor) to pass us a valid IUnitOfWork instance.</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">GetProductCategoriesHandler</span> : <span style="color: #2b91af;">ReadOnlyRequestHandler</span>&lt;<span style="color: #2b91af;">GetProductCategoriesRequest</span>&gt;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">readonly</span> <span style="color: #2b91af;">IRepository</span>&lt;<span style="color: #2b91af;">ProductCategory</span>&gt; repository;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> GetProductCategoriesHandler(<span style="color: #2b91af;">IUnitOfWork</span> unitOfWork, <span style="color: #2b91af;">IRepository</span>&lt;<span style="color: #2b91af;">ProductCategory</span>&gt; repository) </p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; : <span style="color: blue;">base</span>(unitOfWork)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">this</span>.repository = repository;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> AddQueries(<span style="color: #2b91af;">IQueryBatcher</span> queryBatcher, <span style="color: #2b91af;">GetProductCategoriesRequest</span> request)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; queryBatcher.AddCriteria(<span style="color: #a31515;">"categories"</span>, repository.CriteriaForAll());</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: #2b91af;">Response</span> GetResults(<span style="color: #2b91af;">IQueryBatcher</span> queryBatcher, <span style="color: #2b91af;">GetProductCategoriesRequest</span> request)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> categories = queryBatcher.GetEnumerableResult&lt;<span style="color: #2b91af;">ProductCategory</span>&gt;(<span style="color: #a31515;">"categories"</span>);</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">GetProductCategoriesResponse</span> { ProductCategories = categories.ToDTOs() };</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The ReadOnlyRequestHandler class defines two abstract methods: the AddQueries and GetResults method.  Both are passed an instance of IQueryBatcher and the actual request object so you can use the request parameters if there are any.</p>
<p>In the AddQueries method, you simply add the queries this request needs to perform to the batcher (with a string key value of course for later retrieval), and in the GetResults method you can get the results (with the key values used in AddQueries) back from the batcher and you can construct your Response object.  The GetResults method will be called after each ReadOnlyRequestHandler for the current request batch has added the queries to be performed to the batcher.  The queries are then all executed, and each ReadOnlyRequestHandler will have its GetResults method called so each handler can construct the proper response.</p>
<p>And that&#8217;s it basically&#8230; The calling code doesn&#8217;t even change. </p>
<p>Now there are obviously some limitations. If you mix ReadOnlyRequests with other Requests, then each ReadOnlyRequest will be handled as if it were a regular Request and they will each get their very own IQueryBatcher instance.  I don&#8217;t think there&#8217;s any strategy to automagically determine which ReadOnlyRequests can be batched together while still correctly executing the other Requests since those requests might influence the results of ReadOnlyRequests that are present further in the batch.</p>
<p>Anyways, you can find an updated version of the library <a href="http://davybrion.com/blog/stuff/">here</a>.  Check it out, it&#8217;s some pretty slick shit, if i do say so myself <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Note: i only added this stuff today, so the previous build (080729) doesn&#8217;t have this yet, in case you only downloaded that today, and the stats show that some of you actually did download it <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2008/07/batching/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
