Understanding the various options for runtime code generation in C# (Roslyn, CodeDom, Linq Expressions, …?)

不羁岁月 提交于 2019-12-03 20:33:01

I'm not sure I understand your example, nor that code generation is hte best way to improve it's performance.

But if you want to understand the code generation options, first consider your requirements. Performance is what you want, but there is the performance of the code generation, and the performance of the generated code. These are definitelly not the same thing. Then there is the writability and readability of your code. Different options have very different scores on this one.

Your first option is Reflection.Emit, especially DynamicMethod. Reflection.Emit is a pretty low level API, and is pretty efficient (i.e. the code generation has good performance). Furthermore, because you have complete control of the code being generated, you have the potential to generate the most efficient code (or to generate very bad code, obviously). Also, you are not restricted to what a language such as C# allows you to do, the full power of the CLR is at your fingertips. The biggest problem with Reflection.Emit is the large volume of code you need to write, and the deep knowledge of IL required to do so. Writing that code is not easy, nor is afterwards reading or maintaining it.

Linq.Expressions, more specifically the Compile method provide a nice alternative. You can think of this as being essentially a type-safe wrapper around DynamicMethod generation with Reflection.Emit. There is some overhead in generating the code, which would probably not be a big problem. As for freedom of expression, you can do pretty much everything you can do in a normal C# method. You do not have complete control over the generated code, but the quality is generally very good. The biggest advantage of this approach is that it is much easier to write and read a program using this technique.

As for Roslyn, you have the option of generating a syntax tree, or generating C# (or VB) and have it parsed into a syntax tree to be compiled. It is way to early to guess what the performance might be, as we do not have production code available (at the time of writing). Obviously, parsing a syntax tree will have some overhead, and if you are generating a single method Roslyn's ability to generate multiple methods in paralle won't help a lot. Using Roslyn has the potential that it allows for very readable programs though.

As for CodeDom, I would recommend against it. This is a very old API, that (in the current implementation) launches a CSC.exe process to compile your code. I also believe that it does not support the complete C# language.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!