名单 .RemoveAll()效率/编译器优化

问题描述 投票:24回答:3

关于效率,是否有人知道编译器是否足够聪明,不能在以下代码中为循环的每次迭代创建包含1, 3, 5的数组?

var foo = new List<int> { 1, 2, 3, 4, 5 };
foo.RemoveAll(i => new[] { 1, 3, 5 }.Contains(i));

我更喜欢它的可读性,但不是为了性能。

c# arrays list linq compiler-optimization
3个回答
13
投票

答案是不,它没有优化数组的分配

基本上,每次调用谓词时,它都会检查编译器生成的类并初始化一个新数组来调用Contains(如你所见,here

private sealed class <>c
{
    public static readonly <>c <>9 = new <>c();

    public static Predicate<int> <>9__0_0;

    internal bool <M>b__0_0(int i)
    {
        // bam!
        int[] obj = new int[3];
        RuntimeHelpers.InitializeArray(obj, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
        return Enumerable.Contains(obj, i);
    }
}

4
投票

正如@Michael Randall已经写过的那样,看起来它是不可能的。

我同意,你的质疑代码很可读,在RemoveAll方法中有列表。但是要让实例只有一次,我有三个想法:

int[] a = null;
foo.RemoveAll(i => (a ?? (a = new[] { 1, 3, 5 })).Contains(i));

这实际上是你的,几乎不需要外部变量。

 foo = foo.Except(new[] { 1, 3, 5 }).ToList();

这实际上是使用Linq的非常好的解决方案。

 new List<int>{1, 3, 5}.ForEach(x => foo.Remove(x));


 new[] {1, 3, 5}.Iterate(x => foo.Remove(x));

这是我要做的事情。在我的所有代码中,我使用我的扩展方法“迭代”以避免使用foreach。而且,我不想一直“toList”所有的东西来制作一个.ForEach(..)

static class Extensions
{
    public static void Iterate<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
    {
        foreach (var item in source)
        {
            action.Invoke(item);
        }
    }
}

0
投票

由于编译器不那么聪明,我们必须超越他。

var foo = new List<int> { 1, 2, 3, 4, 5 };
var bar = new HashSet<int>() { 1, 3, 5 };
foo.RemoveAll(i => bar.Contains(i));
© www.soinside.com 2019 - 2024. All rights reserved.