函数调用中实例化对象的性能(说明?)



有人能向我解释一下这里的性能差异吗。作为背景,我在Leetcode和我的原始代码(底部(上做了一个回溯问题,在那里我创建了与函数调用内联的新列表,执行时间大约为490ms,但在添加列表之前重新创建列表的更改代码(顶部(执行时间大约是256ms。几乎快两倍?有人能向我解释为什么吗?我不知道这是编译器/优化问题,还是我遗漏了什么。

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上循环时都要实例化一个新的List。

实例化是昂贵的。

最新更新