0

Question is quite simple - Does checking the actual parameters given to a function incur a performance penalty?

Exported library functions usually tend to check actual parameters passed by user code:

if (arg1 == NULL || arg2 == NULL)
    return -EINVAL;

Does this check incur a performance penalty? I tried optimizing some library code by removing these checks from some of the exported function (relying on me being a well behaved user and always passing valid parameters) but I noticed no real improvement.

My first guess would be that branch prediction on modern processors will assume the if branch is not taken and proceed with the code with no real penalty. If this is indeed the reason - what are the limits of such branch prediction mechanisms? Is there any scenario in which eliminating these checks would improve performance? How does this change between a native compiled language such as C and an interpreted or VM language such as Python and Java?

BTW - I realize the importance of checking runtime parameters. I'm just interested on the performance aspect.

smichak
  • 4,716
  • 3
  • 35
  • 47
  • You need to benchmark this kind of thing extensively to really know. There'a no wat to definitively answer this. Also, look into the Linux kernel's `__likely` and `__unlikely` macros. – Jonathon Reinhart Sep 23 '16 at 12:07
  • You might find [this](http://stackoverflow.com/a/11227902/2681632) interesting. – Ilja Everilä Sep 23 '16 at 12:08
  • A better question is whether checking the arguments for `NULL` is doing anything useful. There are *plenty* non-`NULL` pointers that must not be passed to a function expecting a valid input. An `assert()` may be more reasonable. – EOF Sep 23 '16 at 16:45

1 Answers1

1

If the check of arguments is as simple as a value compare the improvement of performance resulting from removing this checks is minimal. If any of the checks are more complex like checking all items of an array or calling other functions to perform check of each parameter then you might see some improvement in performance.

In any well written library this kind of parameter checks should not be time consuming. If you are trying to find the bottleneck that is affecting your development you should benchmark/profile the execution of your code to determine "which line of code/functions" are taking more time to execute and focus on improving them.

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99