Over a million developers have joined DZone.

High Performance Field Clobbering

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

· Performance Zone

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

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.

Learn tips and best practices for optimizing your capacity management strategy with the Market Guide for Capacity Management, brought to you in partnership with BMC.

Topics:
performance ,field ,scenario

Published at DZone with permission of Ayende Rahien, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}