Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance gain while incrementing char pointer over accessing elements by index?

Tags:

c

I'm in a process of refreshing my "C" knowledge. I get that Arrays decay to pointers and how that works. In string processing I keep running in to code that looks like this;

int count_spaces(const char *s)
{
    int count = 0;

    for(; *s != '\0'; s++){
        if(*s == ' '){
            count++;
        }
    }

return count;

}

What performance gain do I get out of my string processing code instead of writing my function as this?

int count_spaces(const char s[])
{
    int count = 0, i;

    for(i = 0; s[i] != '\0'; i++)
    {
        if(s[i] == ' '){
            count++;
        }
    }
return count;

}

Is there an easy lexicon to go by for when to use a pointer and when not to?

like image 333
ultrasounder Avatar asked Dec 15 '15 22:12

ultrasounder


1 Answers

This is compiler dependent. Some compilers may offer a performance gain for one method or the other.

However, it may be useful to look at a specific example. Using gcc -S -O0, the lowest optimized assembly output on my machine gives 3 more instructions for the first function than the second function.

But using the -O3 flag they are optimized to identical assembly files.

Edit: also see bracketing that makes your code as readable and resistant to unlucky errors as possible :)

int count_spaces(const char s[]) {
    int count = 0, i;

    for(i = 0; s[i] != '\0'; i++) {
        if(s[i] == ' ') {
            count ++;
        }
    }
    return count;
}

Edit:

To answer your question clearly: use whichever is most clear to you and whoever may read your code. The performance boost you may get is negligible compared to the benefit of readability and clarity of intention. Leave it to the compiler to squeeze this kind of performance out of your code

like image 195
Dylan Kirkby Avatar answered Sep 21 '22 03:09

Dylan Kirkby