High Performance Field Clobbering
Ayende Rahien provides his insight on performance in a scenario for class re-use.
Join the DZone community and get the full member experience.Join For Free
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:
and here is the simplest option to handle it:
and that gives us:
can we do better?
what happens if we cache the field lookup?
this has significant improvement, right?
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:
and the benchmark result?
that is pretty awesome. for comparison purposes, i also did a static delegate and direct set, to compare the costs.
and those give me:
but i think that 2.5 ns is fast enough for me here.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.