sealed class CodeX.StaticTemplateAttribute

Derived from

Attribute abstract

The annotated interface represents a static template that is used by high-performance code.

The standard object-oriented design principles encourage the use of interfaces and thus the use of dynamic dispatch at runtime (aka. polymorphism). This is the preferred choice for modelling high-level concepts, because it provides optimal flexibility, extensibility and maintainability.

However, some low-level concepts (especially when bare computational performance is important), do not go well with the standard OOP principle. Usually, there is some kind of performance-critical algorithm (i.e. sorting, image manipulation, physics solver) which needs to run with different kinds of input. This can be modelled with standard OOP principles, but doing so will incur performance penalties because dynamic dispatch at runtime (aka. virtual method calls) requires an additional level of indirection. This will have a negative impact on CPU branch-prediction and - more importantly - will prevent compilers from using aggressive optimization, such as inlining, use of intrinsic functions or extended instruction sets.

A static template interface avoids those performance pitfalls, while providing flexibility and extensibility. Such an interface must be implemented as a struct type, which effectively prohibits the use of dynamic dispatch at runtime and guarantees copy-by-value semantic. Instantiation is performed by passing the implementing type as a generic template argument at compile-time. This allows the compiler to infer all information at compile time that is necessary for performing aggressive optimization.

With C++, template instantiation will effectively resolve dynamic dispatch calls into static calls at compile time. With C#, the generated IL will contain callvirt instructions that are annotated with constrained, which allows JIT compilation to resolve dynamic dispatch calls into static calls, before emitting machine-dependent code.