Search code examples
cassemblygoto

Do goto statements in C and assembly break locality of reference thereby decreasing performance?


I wrote a program in C that selects random words from a book in txt file format and prints them out one by one using goto statements. When I run the program it takes about 2 to 3 minutes to start running. Could it be that goto statements break locality of reference and drastically decrease performance? Also does jmp in assembly act as goto breaking locality of reference as well?


Solution

  • This is a very vague question. Gotos might impair locality or might not, it depends on the case. But even when this holds, it is not necessarily bad. For this case, you need to post some code. Take a look at these 2 examples:

    CASE 1:

    for(int i = 0; i<SIZE ; i++){
       if( strcmp(words[i],"key")==0 )
        goto end;
    }
    
    end:
        printf("FOUND!\n");
    
    return 1;
    

    CASE 2:

    int flag = 0;
    
    for(int i = 0; i<SIZE ; i++){
       if( strcmp(words[i],"key")==0 )
        flag = 1;
    }
    
    end:
        if(flag) printf("FOUND!\n");
    

    Of course that CASE 2 enjoys more locality than the first, but CASE 1 would be more efficient (i.e. it would take less time to run), except for the case where "key" is on the last position of the array.