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 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.
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:
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.
Below is a sample function template with five parameters:
five_parameter_function(int a, char* p, int b, char* q, float f) {
____
____
}
Use the following techniques to solve the above problem:
*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.