Search code examples
algorithmcomputer-sciencespace-complexity

What is the Space Complexity of Passing by Reference


I was reading this website to learn about space complexity. It mentioned the following scenario:

A function is written in a language that is pass by value. So whenever an argument is passed, new memory is allocated for the local variable. However, you pass a pointer to a variable instead, so you are passing by reference.

The website said that this would not allocate new space for a local variable, because you are passing by reference, so the variable already exists in memory, and the memory is then shared.

But wouldn't it still create a local variable that was a pointer to the memory location? And, as a result, allocate new memory?


Solution

  • Yes; there is a single word of memory allocated in the stack frame for that call. What they intend to convey is that you're not allocating memory for the existing variable (e.g. 1kb for a 1000-character string). Formally, this allocation is O(1) rather than the O(n) you get from pass by value.

    If you don't consider the stack to be part of the process's memory, then you have a zero-cost allocation for this case. Also, note that O(1) space overhead will not increase the complexity for any algorithm, so it's theoretically okay to ignore. It's valid, although it does smell strange to do so.