What's faster: expression trees or manually emitting IL

Is there a performance difference between creating a method that emits IL directly, as opposed to building an expression tree?

+6
source share
2 answers

Ultimately, the expression tree API is actually just a more familiar API compared to relection.emit, and therefore they are actually equivalent, although I believe there are many things you cannot do in expression trees that you can with using direct reflection.emit.

Reflection.Emit is the fastest overall, but in the same way that the for loop is faster than foreach in general. There are many scenarios in which you can write code that runs faster with reflection.emit than you can use the api expression, but in most cases they should be equivalent.

Now, an API expression does itself a little better than doing things for several reasons.

  • This is more complicated than using direct reflection.emit. You can take an expression tree and rewrite it to add some logic much easier than you can using direct IL
  • Optimizations may be added in the future that you cannot understand what would not happen when using direction reflection.emit.

So, ultimately, I would say that this is a sink. If this is really important, and you know that reflection is good enough, you can usually use some shortcuts in IL that will not use the expression APIs, but other than that, in general use, they should be fairly equivalent.

+6
source

Great and difficult question. Until recently, an expression simply could not handle all the scripts, so in many cases this was not a question. This changes with the introduction of Expression.Block, etc. In most โ€œordinaryโ€ cases, using Expression is probably more than enough, but I admit that I donโ€™t have accurate measurements, simply because although I do a lot of IL, I also target lower-level structures that have no objects luxuries like Expression (and, of course, not Expression.Block). I also tend to use complex โ€œdecoratingโ€ approaches that are well suited for collecting gymnastics in IL, but not necessarily in Expression (indeed, if your IL is atypical enough that the reflector and others struggle with it, then it probably also does not display purely to expression - and my IL tends to be pretty rude).

Sorry, I canโ€™t give you more numerical data - key points:

  • If you have lower-level infrastructure requirements, the issue will be debatable.
  • otherwise you will need to profile
+9
source

Source: https://habr.com/ru/post/944925/


All Articles