Over a million developers have joined DZone.

High Performance Field Clobbering

DZone's Guide to

High Performance Field Clobbering

Ayende Rahien provides his insight on performance in a scenario for class re-use.

Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

So we are using a particular library in a not so standard way. And in order to gain 10x performance benefit we have to reuse a particular class from this library. This class isn’t meant to be reused, but looking at its code, it is clear that it is perfectly possible to do so. All we need is to set the _started field to false and it will be possible to reuse this instance.

So far, so good. Except that the field is private. Now, we can’t just implement our own copy of this, because this is a field in the base class that we are extending to plug our extension to the system. We could try submitting a patch for this, but this is a popular library, and tying ourselves to a particular version would suck. This code has also hasn’t changed since at Jan 2012, so that is pretty stable. And yes, we are aware of the risk in doing this, unsupported, etc.

Now that we decided to do it, the question is how. I created the following epic class:

Image title

And here is the simplest option to handle it:

Image title

And that gives us:

Image title

Can we do better?

What happens if we cache the field lookup?

Image title

This has significant improvement, right?

Image title

But that is still quite high for me. Can we do better still?

Let us try some dynamic code generation. In this case, we can’t use the much easier Expression class to do it, and have to go with direct IL generation, which gives:

Image title

And the benchmark result?

Image title

That is pretty awesome. For comparison purposes, I also did a static delegate and direct set, to compare the costs.

Image title

And those give me:

Image title

But I think that 2.5 ns is fast enough for me here.

Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.

performance ,field ,scenario

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}