Home > Back-end >  How does strlen function works in c?
How does strlen function works in c?

Time:02-15

The source code I found for strlen function in c is the one in below:

int
strlen(string)
    char *string;       /* String whose length is wanted. */
{
    register char *p = string;

    while (1) {
    if (p[0] == 0) {
        return p - string;
    }
    if (p[1] == 0) {
        return p   1 - string;
    }
    if (p[2] == 0) {
        return p   2 - string;
    }
    if (p[3] == 0) {
        return p   3 - string;
    }
    p  = 4;
    }
}

The link is this. I don't understand why the steps are 4. The function jumps 4 bytes by 4 bytes over the string. Why it does this way? It could be implemented like this:

int
strlen(string)
    char *string;       /* String whose length is wanted. */
{
    register char *p = string;

    while (1) {
    if (*p == 0)
        return p - string;
    p  = 1;
    }
}

Is there any performance related reason behind it?

CodePudding user response:

This is called "loop unrolling" and is done purely for performance reasons. Modern compilers are perfectly good at doing their own loop unrolling, so doing it manually is likely going to hurt performance relative to the compiler's generated code.

  • Related