What is an efficient way of passing parameters to a function?

Our goal is to minimize the number of parameters passed to a function in programming.

In C, the compiler will attempt to allocate a processor register to each local variable that you use in a function. When there are more local variables than available registers, the compiler will store excess variables on the processor stack. These excess variables are called swapped out or spilled variables – these are slow to access as compared to variables that are stored in registers.

Registers

Registers allow you to quickly access memory locations. Register allocation is an NP-complete problem.

Register allocation involves taking in a program with an arbitrary number of registers and outputting a program with a finite register set that can fit into the target machine. The register allocation determines which value will reside in the register and which register will hold a certain value.

Register allocation

Minimize the number of spilled variables

To implement a function efficiently, you need to minimize the number of spilled variables while ensuring that the most frequently accessed/ important variables are stored in the registers. Whenever we pass parameters to the functions, we have to consider the following number of parameters passed to the function:

  • maximum four parameters for C
  • maximum three parameters for C++ or JAVA (because of the this pointer)

If you pass more parameters than the ones mentioned above, all excess parameters will be fetched from the DRAM each time as only four registers get allocated for the first four parameters.

Four register rule

  1. Functions with four or fewer arguments are far more efficient to call than functions with five or more arguments.
  2. Functions with more arguments have to access the stack for arguments, both by the caller and callee.

Below is a sample function template with five parameters:

five_parameter_function(int a, char* p, int b, char* q, float f) {
____
____
}

Workarounds

Use the following techniques to solve the above problem:

  1. Use a structure in C or C++ and pass the structure pointer to the calling function.
  2. You can divide a function into multiple functions and the parameters set will get divided too. 3.You can create another object that includes a reference to the respective parameters in the function – this is called object hiding.
  3. You can use a variable number of arguments for definition using *args (a kind of list) and **kwargs (a kind of dictionary) based on what you want to achieve from the function. This will make your code more readable.

In Golang, this is done by using the variadic function.

So, it’s never a better choice to go for more than three parameters, or in some cases, four parameters. By using the above techniques, such as dividing the function based on what you are trying to achieve, you can make your code more efficient.