首页 > 解决方案 > 在函数调用中实例化对象的性能(解释?)

问题描述

谁能在这里向我解释性能差异。作为背景,我在 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);
        }
    }

标签: c#performanceruntime

解决方案


在顶级解决方案中,您在 if 中实例化了一次 List。

在底部解决方案中,每次循环 for 时都会实例化一个新列表。

实例化很昂贵。


推荐阅读