gpt4 book ai didi

c# - .Net Core 3.1 中的 IEnumerable.OrderBy().First() 优化是否记录在任何地方?

转载 作者:行者123 更新时间:2023-12-04 11:44:26 25 4
gpt4 key购买 nike

.Net Core 版本之一(我不确定是哪个)引入了优化,如果您编写这样的代码:

int smallest = new[]{ 7, 2, 4, 6, 0, 1, 6, 9, 8 }.OrderBy(i => i).First();
那么它的复杂度是 O(N)而不是 O(N.Log(N)) .
这在任何地方都有记录吗?如果它不是“官方的”,我不想依赖这种优化。

显示 .Net Core 和 .Net Framework 之间差异的示例代码:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{
static class Program
{
static void Main()
{
int[] test = { 7, 2, 4, 6, 0, 1, 6, 9, 8 };

var comparer = new Comparer();
var _ = test.OrderBy(i => i, comparer).First();
}
}

class Comparer : IComparer<int>
{
public int Compare(int x, int y)
{
Console.WriteLine($"Comparing {x} with {y}");
return x.CompareTo(y);
}
}
}
使用 .Net Framework 在线试用: https://dotnetfiddle.net/XItXYL
使用 .Net Core 在线试用: https://dotnetfiddle.net/swlc0O
.Net Framework 4.8 的输出:
Comparing 0 with 7
Comparing 0 with 8
Comparing 0 with 9
Comparing 0 with 6
Comparing 0 with 1
Comparing 0 with 0
Comparing 0 with 2
Comparing 0 with 6
Comparing 0 with 4
Comparing 0 with 2
Comparing 0 with 0
Comparing 7 with 2
Comparing 7 with 4
Comparing 7 with 6
Comparing 7 with 7
Comparing 7 with 8
Comparing 7 with 9
Comparing 7 with 6
Comparing 7 with 1
Comparing 7 with 7
Comparing 7 with 1
Comparing 9 with 7
Comparing 9 with 9
Comparing 9 with 8
Comparing 7 with 7
Comparing 7 with 8
Comparing 7 with 7
Comparing 6 with 2
Comparing 6 with 4
Comparing 6 with 6
Comparing 6 with 1
Comparing 6 with 6
Comparing 6 with 6
Comparing 6 with 1
Comparing 6 with 6
Comparing 6 with 6
Comparing 4 with 2
Comparing 4 with 4
Comparing 4 with 1
Comparing 2 with 2
Comparing 2 with 1
.Net Core 3.1 的输出:
Comparing 2 with 7
Comparing 4 with 2
Comparing 6 with 2
Comparing 0 with 2
Comparing 1 with 0
Comparing 6 with 0
Comparing 9 with 0
Comparing 8 with 0

最佳答案

问题“此优化是否记录在案”的答案是:是(有点)。
https://github.com/dotnet/runtime/issues/14867用于讨论和链接到实现它的 GitHub 提交。

关于c# - .Net Core 3.1 中的 IEnumerable.OrderBy().First() 优化是否记录在任何地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64665974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com