Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does the strlen function need to be recalculated every round of the for loop? #138

Open
Mserhatarslan opened this issue Feb 1, 2024 · 1 comment

Comments

@Mserhatarslan
Copy link

Mserhatarslan commented Feb 1, 2024

strlen(example) function is called in each iteration of the loop to determine the length of the string example. However, calculating the length of the string repeatedly in each iteration can be inefficient, especially if the length remains constant throughout the loop.

Virtual-Assistant/analysis.c

for (int iter_char = 0; iter_char < strlen(example); iter_char++) {

int len = strlen(example);

for (int iter_char = 0; iter_char < len; iter_char++) {
    example[iter_char] = tolower(example[iter_char]);
    if (example[iter_char] == ' ') {
        if (example[iter_char + 1] != ' ') {
            split[word][character] = '\0';
            character = 0;
            word++;
        }
        continue;
    } else {
        split[word][character++] = example[iter_char];
    }
}

By calculating the length of the string outside the loop and storing it in the variable len, you avoid the overhead of recomputing the length in each iteration. This can lead to a significant improvement in performance, especially for long strings.

@mdahamshi
Copy link

mdahamshi commented Mar 28, 2024

I agree with that, you want to make sure example length doesn't change until the loop is done...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants