是否有一个洗牌的IEnumerable这两种算法之间的性能差异? [英] Is there a performance difference between these two algorithms for shuffling an IEnumerable?

查看:98
本文介绍了是否有一个洗牌的IEnumerable这两种算法之间的性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个问题给出类似的algorthims洗牌一个IEnumerable

These two questions give similar algorthims for shuffling an IEnumerable:

  • C#: Is using Random and OrderBy a good shuffle algorithm?
  • Can you enumerate a collection in C# out of order?

下面是两种方法,并排侧:

Here are the two methods side-by-side:

public static IEnumerable<T> Shuffle1<T> (this IEnumerable<T> source)
{
    Random random = new Random ();
    T [] copy = source.ToArray ();

    for (int i = copy.Length - 1; i >= 0; i--) {
        int index = random.Next (i + 1);
        yield return copy [index];
        copy [index] = copy [i];
    }
}


public static IEnumerable<T> Shuffle2<T> (this IEnumerable<T> source)
{
    Random random = new Random ();
    List<T> copy = source.ToList ();

    while (copy.Count > 0) {
        int index = random.Next (copy.Count);
        yield return copy [index];
        copy.RemoveAt (index);
    }
}



他们基本上是相同的,除了一个使用列表,以及一个使用数组。从概念上讲,第二个看起来更清晰。但是,有没有被使用数组获得了显着的性能优势?即使大O的时间是一样的,如果是快好几倍,它可以使一个明显的区别。

They are basically identical, except one uses a List, and one uses an array. Conceptually, the second one seems more clear to me. But is there a substantial performance benefit to be gained from using an array? Even if the Big-O time is the same, if it is several times faster, it could make a noticeable difference.

推荐答案

第二个版本可能会因为RemoveAt移除的有点慢。列表是真的,当你添加元素到他们成长的数组,正因为如此,插入和删除中间慢(其实,MSDN指出RemoveAt移除了一个O(n)的复杂性)。

The second version will probably be a bit slower because of RemoveAt. Lists are really arrays that grow when you add elements to them, and as such, insertion and removal in the middle is slow (in fact, MSDN states that RemoveAt has an O(n) complexity).

总之,最好是简单地使用一个分析器来比较这两种方法。

Anyway, the best would be to simply use a profiler to compare both methods.

这篇关于是否有一个洗牌的IEnumerable这两种算法之间的性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆