最佳实践
发表于:2025-10-13 | 分类: Dotnet
字数统计: 321 | 阅读时长: 1分钟 | 阅读量:

最佳实践

主要基于 dotnet 源码中的代码优化。

% 取模运算符

Intel处理器对求%运算有较高的指令级延迟,改为比较&减法可平均提升 foreach 2x速度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\Queue.cs 451L
// 运行100_000_000次
int Modulo(a, b) // 152ms
{
return a % b;
}

// 推荐
int CompareSub(a, b) // 133ms
{
if (a >= b)
a -= b;
return a;
}

IEnumerable<T>

某些迭代集合具有延迟加载特性,大幅提升性能。

1
2
3
4
5
6
7
8
9
10
11
// 加载全部文件到内存中(1647843个文件)
void GetFiles() // 10537ms
{
var files = Directory.GetFiles("D:\\AbDir", "*.ab", SearchOption.AllDirectories);
}

// 推荐:仅返回枚举器,用时延迟加载
void EnumerateFiles() // 956ms
{
var files = Directory.EnumerateFiles("D:\\AbDir", "*.ab", SearchOption.AllDirectories);
}

?: 三元运算符

实际上比简单的比较&分支更慢,JIT会生成更好的底层代码。

1
2
3
4
5
6
7
8
9
10
11
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\Queue.cs 333L
private void MoveNext(ref int index)
{
// int tmp = index + 1 == _array.Length ? 0 : index + 1;
int tmp = index + 1;
if (tmp == _array.Length)
{
tmp = 0;
}
index = tmp;
}

质数判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\HashHelpers.cs 40L
public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
int limit = (int)Math.Sqrt(candidate);
for (int divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
}
return true;
}
return candidate == 2;
}
上一篇:
哈希集合
下一篇:
队列