Issues in the Pass by Value

Learn the shortcomings of the pass by value strategy.

Introduction

Pass by value is neat and easy! It does the job perfectly if we need to pass some information for the called function to read.

Pass by value works by creating copies of the arguments and then passing those copies to the called function.

Having to create a copy introduces two drawbacks. We will discuss them now.

Changing the arguments

The first drawback is that we can not propagate the changes from the called function (callee) to the caller. We already saw this in the previous lesson.

Too many copies

The second drawback is more subtle. Even if the code works fine, it may not be optimal.

This issue is not immediately clear if we pass integers or floats, as these variables have small sizes, and copying them is extremely fast. But if we have a significant amount of data, the time it takes to copy the data from one point to another may slow down our application.

If we don’t need to propagate the changes made by the callee back inside the caller, then the copy is unneeded, and it will be performed in vain just for that memory to get deallocated when the function finishes.

Consider the following example:

  • We’re receiving requests from the outside, where each request contains a significant amount of data.
  • To process this data, we have to pass it through a chain of filters, where each filter performs one type of validation. For example, one filter may check the size of the payload data, another filter may check if it is valid, and another filter may check if the data comes from a trusted source.
  • In reality, we could have as many filters as possible, depending on the requirements of our application.
  • View each filter as a function that takes the data as input and returns 1 or 0. It returns 1 if the data passed the checks and 0 otherwise.
filter_k(data)
{
    if check_k(data)
        return 1

    return 0
}

Imagine we have a chain of 100 filters:

//when data is received
filter_1(data)
filter_2(data)
...
filter_100(data)

Then for each filter call, a copy of data is performed. If data is huge, well copy gigabytes or terabytes of data 100 times for no reason! The filter functions don't change data` in any way. They perform a check and return.

Check the following animation for a schematic view.

Get hands-on with 1400+ tech skills courses.