Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Any decent C/C++ compiler will give the same code. For example, this:

    int f1(int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            int x = i + i;
            sum = x - i;
        }
        return sum;
    }

    int f2(int n) {
        int sum = 0;
        int x;
        for (int i = 0; i < n; i++) {
            x = i + i;
            sum = x - i;
        }
        return sum;
    }
when compiled with 'gcc -O -S' gives:

            .file       "loop.c"
            .text
            .globl      f1
            .type       f1, @function
    f1:
    .LFB0:
            .cfi_startproc
            testl       %edi, %edi
            jle .L4
            movl        $0, %eax
    .L3:
            addl        $1, %eax
            cmpl        %eax, %edi
            jne .L3
            subl        $1, %eax
            ret
    .L4:
            movl        $0, %eax
            ret
            .cfi_endproc
    .LFE0:
            .size       f1, .-f1
            .globl      f2
            .type       f2, @function
    f2:
    .LFB1:
            .cfi_startproc
            testl       %edi, %edi
            jle .L9
            movl        $0, %eax
    .L8:
            addl        $1, %eax
            cmpl        %eax, %edi
            jne .L8
            subl        $1, %eax
            ret
    .L9:
            movl        $0, %eax
            ret
            .cfi_endproc
    .LFE1:
            .size       f2, .-f2
            .ident      "GCC: (GNU) 7.2.0"
            .section    .note.GNU-stack,"",@progbits
Even when compiled without optimization, the generated assembly was the same, though it was messier so I don't show it.


Okay cool, so Go seems to be standing alone here without that optimization :-/

Can someone please call Rob Pike? We are discussing Golang 2.0 already and still don't have 'common' compiler optimizations... ;-) joke


I suspect llgo and gccgo do this already




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: