Home > Enterprise >  Optimization - Best practice to return an empty string in C
Optimization - Best practice to return an empty string in C

Time:11-18

I have two functions, and both can return an empty string, so what is the best practice to save memory and avoid duplicated .txt empty string?

Example

const char* function_one() {
    return "";
}
const char* function_two() {
    return "";
}
int main() {
    printf("One: %s\n", function_one());
    printf("Two: %s\n", function_two());
}

Is this optimization correct ?

const char* empty = "";
const char* function_one() {
    return empty;
}
const char* function_two() {
    return empty;
}
int main() {
    printf("One: %s\n", function_one());
    printf("Two: %s\n", function_two());
}

CodePudding user response:

Usually compilers by default store identical string literals as one string literal in the literal pool. In any case they provide an option that can control that.

So this code

const char* function_one() {
    return "";
}
const char* function_two() {
    return "";
}

in fact is equivalent to this code

const char* empty = "";
const char* function_one() {
    return empty;
}
const char* function_two() {
    return empty;
}

except in the last code there is created a redundant global variable.

You can check the default strategy of your compiler for example the following wat

#include <stdio.h>

const char* function_one() {
    return "";
}
const char* function_two() {
    return "";
}

int main(void) {
    printf( "%s\n", function_one() == function_two() ? "equal" : "not equal" );
}

CodePudding user response:

what is the best practice to save memory and avoid duplicated .txt empty string?

The best practice is to not fixate on the one char it takes represent an empty string, nor even the handful of additional bytes that might accompany it for alignment purposes. It is much more valuable to make your code clear, and using string literals serves that objective in this case.

Even so, this probably is not an either / or situation. It is likely that your compiler will merge identical string literals, so that it's not an issue in the first place.

More generally, don't go out of your way to attempt hand optimization. Write clean code using algorithms and data structures appropriate for your objectives, implemented with reasonable efficiency. Revisit that only when you determine that there is an actual problem to be solved by micro-optimizations such as you are considering.

  • Related