为什么F#表达式树生成比C#慢得多,它可以更快吗?

时间:2015-09-15 18:07:31

标签: c# f# expression

在F#中构建一个简单的表达式树:

type Quote<'T> = 
    static member X(exp:Expression<Func<'T,'a>>) = exp

type T = { x:int }

[<EntryPoint>]
let main argv = 
    for _ in [1..4] do
        let sw = Stopwatch.StartNew()
        [for i in [1..10000] -> Quote.X(fun x -> x.x = i)] |> ignore
        printfn "Elapsed: %A" sw.Elapsed
    0 // return an integer exit code

在.NET和mono上, x35 比这个C#慢

class Program
{
    class T {public int x {get;set;}}

    static void Main(string[] args)
    {
        for (var ii = 0; ii < 4; ii++)
        {
            var sw = Stopwatch.StartNew();
            Enumerable.Range(0,10000)
                .Select(i => (Expression<Func<T,bool>>)(t => t.x == i ))
                .ToList();
            Console.WriteLine("Ellapsed: {0}", sw.Elapsed);
        }
    }
}

任何人都知道为什么会这样,如果有什么我可以做些什么来改善它? 解决方案是在github上,以防有人想尝试:https://github.com/et1975/ExpressionTrees

1 个答案:

答案 0 :(得分:0)

您可以在F#中使用System.Linq.Expressions.Expression,但它看起来很难看:

 Your branch and 'origin/logs' have diverged,
    and have 621 and 1 different commit each, respectively.
      (use "git pull" to merge the remote branch into yours)