Chapo144
Chapo144

Reputation: 102

Which code is more efficient in memory/time complexity

It's said that when we pass an array to a function then only copy of that array is passed to the function. If we modify the array inside that function then original array would also be affected. So will case 1 take equal memory or it would consume significantly higher memory when compared to case 2 ?

//Case 1:-
int sum(vector<int> v)
{
...
}
//Case 2:-
int sum(vector<int> &v)
{
...
}

Upvotes: 1

Views: 124

Answers (1)

Stefan Riedel
Stefan Riedel

Reputation: 801

You're passing a std::vector, not an Array. The first case will take a copy of that vector (copying all elements to a new instance of std::vector<int>), while the second will just take a reference to the original vector.

It's quite obvious that the second case will be more efficient (both performance and memory wise) than the first one, because no copying will be done and you don't end up having two vectors.

But even better (not for performance but code design) would be

int sum(const std::vector<int> &v)
{
...
}

Because you're not modifying the vector.

PS: Why is "using namespace std;" considered bad practice

Upvotes: 5

Related Questions