c# - 在函数调用中实例化对象的性能(解释?)
问题描述
谁能在这里向我解释性能差异。作为背景,我在 Leetcode 和我的原始代码(底部)上做一个回溯问题,我在其中创建与函数调用内联的新列表的执行时间大约为 490 毫秒,但更改的代码(顶部)在我添加之前重新创建列表执行时间约为 256 毫秒。几乎快两倍?谁能向我解释为什么会这样,我不知道这是编译器/优化问题还是我遗漏了什么。
private void backtracking(List<IList<int>> retList, List<int> tempList, int k, int n, int start) {
if(tempList.Count==k) {
List<int> combo = new List<int>(tempList); //*** <- faster with this line ***
retList.Add(combo);
return;
}
for(var i=start; i<n; i++) {
tempList.Add(i+1);
backtracking(retList, tempList, k, n, i+1);
tempList.RemoveAt(tempList.Count-1);
}
}
private void backtracking(List<IList<int>> retList, List<int> tempList, int k, int n, int start) {
if(tempList.Count==k) {
retList.Add(tempList);
return;
}
for(var i=start; i<n; i++) {
tempList.Add(i+1);
backtracking(retList, new List<int>(tempList), k, n, i+1); //*** <- Slower with this line ***
tempList.RemoveAt(tempList.Count-1);
}
}
解决方案
在顶级解决方案中,您在 if 中实例化了一次 List。
在底部解决方案中,每次循环 for 时都会实例化一个新列表。
实例化很昂贵。
推荐阅读
- go - 动态编程 - 带有记忆的树递归
- google-apps-script - 图片功能不生成二维码。如何从二维码生成url中获取数据?
- kubernetes - 可以在 OpenShift 服务中同时包含 alpha 和 beta 注释吗?
- kubernetes - 如何将从 .txt 创建的 configmap 添加到 pod?
- java - Java Swing actionPerformed() 跳过可视化
- python - 如何在 django 过滤器中编辑字段名称,并添加样式
- java - 在 HiDPI 屏幕上的 IntelliJ Idea Community 中运行 Swing 应用程序
- python - 异常值:类型字符变化的值太长(2)
- vba - 在 MS Word 中将项目符号列表转换为 SmartArt 的宏
- javascript - 即使在 React/Node/Passport 上添加 CORS 选项以进行 Google 身份验证后,仍面临 CORS 错误