c++cdelphi

What Are the Drawbacks of Functions with Many Parameters (e.g., ~40), Specifically Regarding Performance?


In a project, I encountered a function with around 40 parameters. While I understand the maintainability concerns, I’m specifically curious about the performance impact, including:

Are there any compiler optimizations or best practices (e.g., using var, const, or pointers) to mitigate these issues? Insights or benchmarks would be appreciated!


Solution

  • Memory usage: Does passing many parameters strain the stack or heap?

    It depends on ABI and calling convention, as well as the variable types involved, but generally you can pass up to a certain amount in registers and the rest will get passed on the stack. So it is inefficient and causes stack peak usages that may not be ideal.

    Call overhead: Does the function call become significantly slower, especially with large structs or objects?

    Generally it does. Unless the compiler can inline the function.

    Cache performance: Can this impact CPU cache efficiency?

    The main concern there is that parameters are copied from all over into the stack space, so the data sources are unlikely to be present in cache together, if at all.

    Platform-specific differences: Are some architectures (e.g., ARM, x86) more affected?

    This is particularly troublesome on low-end ISA like microcontrollers with smaller stacks. Cortex M or smaller, like 8/16 bitters. Apart from poor performance you also risk stack overflows.

    Are there any compiler optimizations or best practices (e.g., using var, const, or pointers) to mitigate these issues? Insights or benchmarks would be appreciated!

    Inlining optimizations might eliminate the overhead of copying all the arguments. So by forcing an inline call you could probably speed up the code quite a bit.

    Otherwise best practices is that 8 or so parameters is the upper limit from where maintenance as well as performance will start to suffer. At that point you really need to consider placing parameters in structs/classes instead and pass the struct by reference. Another rule of thumb is to never pass a struct/class by value unless you absolutely need to make a hardcopy of it.

    (Also, a compiler is not required to support more than 127 parameters, but if you've managed to get that many I think the compiler limits are the least of your problems.)


    Summary:
    This is bad in almost every possible way. Unreadable, unmaintainable, slow, dangerous, memory consuming.