2013Asker
2013Asker

Reputation: 2058

Does using several small functions in a program affect performance?

If a C program consists of several small functions like:

int isLetter(const char c){
    if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
        return 1;
    }
    return 0;
}

int isNumber(const char c){
    if(c >= '0' && c <= '9'){
        return 1;
    }
    return 0;
}

will it be less efficient than a similar program implementing the code inline?

Upvotes: 1

Views: 211

Answers (3)

zaadeh
zaadeh

Reputation: 1861

You can write a function and declare it as inline and let compiler automatically inline it for you.

also for the functions you are using there are equivalents in a standard library, ctype.h if I remember correctly.

Upvotes: 0

user395760
user395760

Reputation:

No, it will not be less efficient. It will either be equally efficient, or more efficient. Compilers inline small functions autonomously, and their heuristics are pretty good. Moreover, even if the compiler's inlining decisions turn out to be suboptimal, you don't have to drop to macros or manual inlining to get better performance - in virtually any major compiler, there are ways to force or prevent inlining of a function, and you still get the benefits of a function over macros and manual code.

Upvotes: 2

Chris Hayes
Chris Hayes

Reputation: 12020

That is a question whose answer depends on a lot of situational variables. If the function is called rarely, the compiler may inline it automatically to increase code locality and remove the overhead of a function call; if it is called often, inlining the function's code would increase the size of your program and reduce cache efficiency. There is a fine balance to be struck, one which the compiler is generally the most qualified to find.

That being said, unless you are working on an embedded system with stringent memory requirements, don't even think about this issue. Focus on making your code readable and reusable, and only go back to optimize it when you discover there's a problem. Premature optimization is a waste of development time and can often lead to you introducing bugs as you sacrifice maintainability for unneeded performance improvements.

Upvotes: 5

Related Questions