相关疑难解决方法(0)

三元运算符的速度是if-else块的两倍?

我读的是无处不在三元运营商应该是比快,或至少一样的,它的等效if- else块.

但是,我做了以下测试,发现事实并非如此:

Random r = new Random();
int[] array = new int[20000000];
for(int i = 0; i < array.Length; i++)
{
    array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);

long value = 0;
DateTime begin = DateTime.UtcNow;

foreach (int i in array)
{
    if (i > 0)
    {
        value += 2;
    }
    else
    {
        value += 3;
    }
    // if-else block above takes on average 85 ms

    // OR I can use a ternary operator:
    // value += …
Run Code Online (Sandbox Code Playgroud)

c# performance conditional-operator

245
推荐指数
6
解决办法
4万
查看次数

有效地消除.NET表达式树中的常见子表达式

我编写了一个DSL和一个从中生成.NET表达式树的编译器.树中的所有表达式都是无副作用的,并且表达式保证是"非语句"表达式(没有本地,循环,块等).(编辑:树可能包括文字,属性访问,标准操作符和函数调用 - 这可能正在做一些奇特的事情,如内部的memoization,但外部副作用是免费的).

现在我想对它执行"Common sub-expression elimination"优化.

例如,给定一个对应于C#lambda的树:

foo =>      (foo.Bar * 5 + foo.Baz * 2 > 7) 
         || (foo.Bar * 5 + foo.Baz * 2 < 3)  
         || (foo.Bar * 5 + 3 == foo.Xyz)
Run Code Online (Sandbox Code Playgroud)

...我想生成树等价的(忽略一些短路语义被忽略的事实):

foo =>
{
     var local1 = foo.Bar * 5;

     // Notice that this local depends on the first one.        
     var local2 = local1 + foo.Baz * 2; 

     // Notice that no unnecessary locals have been generated.
     return local2 > 7 || …
Run Code Online (Sandbox Code Playgroud)

.net c# algorithm optimization expression-trees

17
推荐指数
2
解决办法
1282
查看次数