c# - C# - Is overloading methods with different types more performant than using type checking in a single method?
问题描述
Say I have this:
public void DoThing (string text)
{
DoThingWithText(text);
}
public void DoThing (int number)
{
DoThingWithNumbers(number);
}
And compare it to this:
public void DoThing (object obj)
{
if (obj is string text)
DoThingWithText(text);
if (obj is int number)
DoThingWithNumbers(number);
}
Would there be a performance difference here, and if so how significant?
解决方案
会有性能差异。使用特定于类型的方法会更快,但除非每秒执行数百次,否则差异不会很大。
您创建的方法和类越动态和通用,处理它的计算机上的 CPU 就越重。我想如果它在慢速计算机上运行它可能会产生更大的不同。
正如 DavidG 建议的那样,您可以尝试自己运行性能测试。您可以在运行一堆这些方法之前存储 DateTime.Now 并使用对象的类型测试进行另一个测试,然后使用新的 DateTime.Now 输出差异。
推荐阅读
- android - Android 原生合约测试
- javascript - JavaScript 中最小的未使用 ID
- javascript - axios 无法发送带有 cookie 的请求
- java - 使用关联程序打开文件不会在引号中发送其路径
- python - 如何使用自动映射正确处理多个连接路径?
- angular - Angular SVG 图标不适用于 Angular Universal 项目延迟加载模块
- php - 为什么 PHP DateTime->add(DateInterval) 在夏令时转换失败?
- c# - 在 Azure 函数中获取要读取的文件路径
- r - 如何通过使用 R for 循环调用函数来填充空矩阵?
- python - 在 Docker 中设置 $HOME 路径