2

I am using F# Code Quotations for the purpose of producing an executable .NET library via either LINQ expression trees or FSharp.Compiler.Services.

I can author/create most of the AST needed using typed quotations but am struggling with a particular area as the expression could resolve to multiple types - hence am considering untyped code quotations.

I appreciate from this SO question the advantages of typed expressions from a safety point of view but my main concern at this point is runtime performance.

  1. Is it a meta-programming "code smell" if your expression could resolve to multiple types?

  2. Will it make any difference to runtime performance (in .NET) if I use typed versus untyped quotations/expressions

Community
  • 1
  • 1
Sam
  • 2,745
  • 3
  • 20
  • 42
  • 2
    As with most questions regarding performance: *it depends*. Have you tried to measure the difference? – Mark Seemann Jun 30 '15 at 10:25
  • In one (of many potential) applications of my testing I wasn't seeing a difference in performance - this *surprised* me. My question is: should I be surprised? If untyped expressions can figure out their types at generation/compile time then perhaps performance would be equivalent. – Sam Jun 30 '15 at 13:47

1 Answers1

1

If you're comparing just untyped and typed F# quotations (that is, the Expr and Expr<'T> types), then there won't be any real difference. The advantage of typed quotations is that they can (partly) check at compile time that you are constructing a correct quotation, but the underlying representation is actually exactly the same.

If you look at the definition of Expr<'T> in the source code, you can see that it is actually just a lightweight wrapper over Expr (which has an additional type parameter, but otherwise represents exactly the same thing).

If you are interested in compiling code more generally then here are a few points:

  • F# quotations translate to LINQ Expression trees and so there is an additional step. Also, this is generating slower code than the F# compiler.

  • Working with LINQ Expression trees is harder than using F# quotations, so choosing between this approach and quotations is tricky.

  • F# Compiler Service gives you direct access to the compiler, but the best documented API is to compile strings (still, this might be a better choice, because it generates faster code).

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Thanks. So it sounds like *how* I compile them is going to have an effect and `typed vs untyped` not at all really. The two libraries I have been looking at are: (1) FSharp.Quotations.Evaluator (uses LINQ expression trees) which gives better performance than the built-in LINQ compiler and (2) QuotationCompiler which uses an old version of FSharp.Compiler.Services - seems like this one would be best in the long-term then...? – Sam Jun 30 '15 at 15:34