mystackoverflow1212
mystackoverflow1212

Reputation: 157

Performance of instantiating objects in function call (Explanation?)

Can anyone explain to me the performance differences here. For background, I'm doing a backtracking problem on Leetcode and my original code (bottom) where I create the new list inline with the function call performs at around 490ms but the changed code (top) where I recreate the list before I add it performs at around 256ms. Almost twice as fast? Can anyone explain to me why that is, I don't know if it's a compiler/optimization issue or if I'm missing something.

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);
        }
    }

Upvotes: 0

Views: 33

Answers (1)

Elan Sanchez
Elan Sanchez

Reputation: 120

In the top solution you instantiated a List once inside an if.

In the bottom solution you are instantiating a new List every time you loop over the for.

Instantiation is expensive.

Upvotes: 1

Related Questions