High hopes, and crushed dreams

I think that there is a fundamental law of the universe at work in programming, and it goes something like this.  “Everything is much harder than it looks at first glance.”

My troubles started when I decided that I needed a custom serializer or at least some serialization extension points in order to better optimize the way that NHibernate.Remote transmits its data.  Currently I am letting the NetDataContractSerializer do all the work and I am using reflection later to walk the object graph and do things such as update the session on lazy items and synchronize objects that are supposed to be reference equal.  All in all it’s a lofty goal.

I began to dig into the serialization mechanism to look for extension points in the NetDataContractSerializer.  To my dismay though, most of the applicable classes were internal, sealed or didn’t contain anything usefull.  I thought I was out of luck until I came upon Serialization surrogates.  In effect this allows you to attach a serializer/deserializer to an object type (or all object types) and push part of the serialization process through your own code.  This was really close to what I wanted as it would allow me to examine individual objects as they were being serialized and deserialized.  This would mean no more walking the object graph and should net a nice little performance gain.  Yes? actuall NO.

After wiring in some loose code to extract object data and such I tested it to see if it would actually work.  It actually did work, amazing.  Then I fired up Ants to see what the performance was, and to my dismay it was 26x slower.  This was for sure not acceptable as I was hoping to see a performance gain.  I did a more detailed analysis using Ants to figure out where my code went wrong and to my amazement it was not in my code but in MS’s NetDataContractSerializer.  The  SurrogateDataContract which is responsible for getting the data to my custom SerializationSurrogate is incredibly slow, and it doesn’t look as if there is anything I can do about it.

Sigh… So I’m back to square one here.  Leave the reflection code in place as it is already working,  write my own serializer from scratch (Bleh), or start emitting IL code to hack the NetDataContractSerializer?

Leave a Reply