Search code examples
c#attributesinteroplow-level

Define attributes as compile-time data?


I'm writing classes to be a "higher-level" representation of some binary structures as binary files, tcp packets, etc.

For this, and for the sake of readability, that would be very nice if I could define some custom attribute to determine some information about each class' field (e.g. the offset of that field in the binary buffer, the size of the field, etc).

I could accomplish this by declaring constant integers, but IMHO the code would be very ugly and mucky. So I thought about using attributes, which are a very elegant way to accomplish what I want. Features like the InteropServices.Marshal actually uses attributes (as StructLayout, MarshalAs and FieldOffset) to accomplish something very similar to what I want, so I can only assume the performance tradeoff is advantageous compared to the gain of readability (please correct me if I'm wrong).

So, how the forementioned InteropServices' attributes are handled by the compiler/CLR?

Do you guys think the forementioned tradeoff is worth? If yes, the best way to deal with the attributes is using the default method using Refletion? I'm assuming that there could be other ways to access attributes rather than Reflection because I know this is a bit expensive and Marshal uses it in almost every method.

Any helpful thought would be very appreciated, thanks.


Solution

  • What you are proposing sounds reasonable assuming the parallels to the Interop are as clear as you are describing. To avoid the performance issues of using reflection for every property access you can use reflection once, maybe via a static constructor, and build compiled Expressions for each property instead. The performance should be the equivalent of calling a virtual method I would think.

    Here is a link to a blog post denoting the performance differences between different dynamic invocation types. Compiled expressions are ~10x faster then cached reflection and "only" 2x slower then compiled property access.

    http://www.palmmedia.de/Blog/2012/2/4/reflection-vs-compiled-expressions-vs-delegates-performance-comparision