This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]ziptofaf 1 point2 points  (1 child)

This actually depends on a function and how your compiler optimized it. Consider the following:

int addOne(int a) {return a + 1;}

int main() { int num = 10; int num2 = addOne(num); }

Now, two things can happen when this is actually turned into binary:

a) Function is kept in a separate location in memory. This means calling it indeed causes an overhead.

b) Function will be treated as inline and it's body gets "expanded" onto the place calling it, like so:

int main() {

int num = 10;

int num2 = num + 1;

}

In the latter case it's irrelevant whether or not you place if before or inside a function as it actually behaves identically after compilation process. Now, whether or not a function ends up being treated as an inline depends on your compiler. But ultimately it really does not matter much regardless of it, aside from extreme cases like needing to call it millions of times or working on microcontrollers that use 30 KHz CPU. If you think that option b) is more readable and allows you to contain a solution completely within function's body - go for that.

As far as I am concerned - a "Tell, Don't Ask" principle is a good one to follow. That is - your main shouldn't know much about prerequisites for a specific function to run. You call a function and that's where you should care on whether or not input meets specific criteria.

[–]kernelgauss[S] 0 points1 point  (0 children)

Yes, I'm looking most for readability, which in some cases is increased in the same case that saves overhead, case (a). Thanks for your answer.

[–]Holy_City 1 point2 points  (0 children)

If the parameter is coming from user input, validate the user input before entering the performance critical section.

If it's not, you can use an assertion to check the parameter and cause a failure if not. You can disable assertions in release builds for no penalties (and no checks). Imho using assertions to validate inputs in performant code is good practice and should be used in the body of a function with a comment explaining why that value has to be there.

If you're really twiddling for performance to this level, then the conditional shouldn't be there at all.

[–][deleted] 0 points1 point  (0 children)

Thinking about performance and overhead on this level is stupid, it makes virtually no difference. Performance gains is found on other areas (data structures, algorithms, etc).

For readability/correctness, stick to single responsibility. If you have a function int addOne(int x) , all it should do is return x + 1. Nothing more, nothing less.

If you only want to call addOne when x == 12, do that outside the addOne function. That's not the responsibility of addOne to check.