Execution-Time Code Generation in C#: A Fast Custom C# Class

Rather than calling the evaluate function directly like in the previous example, you can change the code so that the custom class implements the interface. After the assembly is loaded and an instance of the class is created, it will be cast to the interface, and that interface will be returned to the driver program.

This approach has two benefits. First, you’ll call directly through the interface, so you avoid the overhead of Type.InvokeMember(). Second, instead of the driver calling the class evaluation function, which then called the custom function, the driver will call the custom function directly. When you try this example, you get the results shown in Table 32-3.

That gives a nice performance increase for small polynomials. For large ones, however, it turns out the function is so big that it doesn’t fit into the cache and therefore gets slower than the simple method.

This has a problem, however. There’s approximately half a second of overhead to write the file, compile it, and read in the resulting assembly. That’s fine if each polynomial is evaluated many times but not if each one is evaluated only a few times.

Also, because this technique involves C# code, the compiler must be present on the system on which the code executes. Depending on where the application will run, this may be a problem.

What’s needed is a way to get rid of the overhead and the dependency on the C# compiler.

Source: Gunnerson Eric, Wienholt Nick (2005), A Programmer’s Introduction to C# 2.0, Apress; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *