M7 发帖数: 219 | 1 这里有两个shuffle方法。第一个通过排序(乱序),第二个是标准的Fisher-Yates
shuffle, which has linear performance.
public static IEnumerable Shuffle(this IEnumerable
collection)
{
Random random = new Random();
return collection.OrderBy(item => random.Next());
}
public static IEnumerable FastShuffle(this IEnumerable
collection)
{
T[] buffer = collection.ToArray();
Random random = new Random();
for (int i = 0; i < buffer.Length; i++)
{
int j = random.Next(i, buffer.Length);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
实验表明第一个Shuffle也非常快,和FastShuffle的差别非常小:
string array of size 50,000: shuffle, 1 milliseconds; fastshuffle, 2
milliseconds.
string array of size 5,000,000: shuffle, 1 milliseconds; fastshuffle, ~0
milliseconds.
时间是用Stopwatch获得的。
请问OrderBy里面是不是有特别的优化,如果是sort, 怎么会这么快? | h*******s 发帖数: 8454 | 2 这是c#还是java代码啊,看着像c#?
为啥不洗个1000次看平均时间,一次能说明问题么
【在 M7 的大作中提到】 : 这里有两个shuffle方法。第一个通过排序(乱序),第二个是标准的Fisher-Yates : shuffle, which has linear performance. : public static IEnumerable Shuffle(this IEnumerable : collection) : { : Random random = new Random(); : return collection.OrderBy(item => random.Next()); : } : public static IEnumerable FastShuffle(this IEnumerable : collection)
| M7 发帖数: 219 | 3 是C#. 我重复了很多次,给出结果是typical的。
【在 h*******s 的大作中提到】 : 这是c#还是java代码啊,看着像c#? : 为啥不洗个1000次看平均时间,一次能说明问题么
| t****t 发帖数: 6806 | 4 不是你挑typical的结果, 是你要拿1000次(或者1000000次)的总时间或者平均时间
【在 M7 的大作中提到】 : 是C#. 我重复了很多次,给出结果是typical的。
| s***o 发帖数: 2191 | 5 Did you actually enumerate the result set? keep in mind that OrderBy is
implemented using deferred execution, which means it just returns a query
object that can be executed later to get the actual result (e.g. when you do
a foreach) |
|