Are const_iterators faster?

后端 未结 11 1864
挽巷
挽巷 2020-11-30 02:04

Our coding guidelines prefer const_iterator, because they are a little faster compared to a normal iterator. It seems like the compiler optimizes t

11条回答
  •  抹茶落季
    2020-11-30 02:22

    They should be identical, as constness is a compile-time check.

    To prove to myself there were no quirks, I took anon's code, modified it to use clock_gettime, added an outer loop to avoid caching biases, and ran it many times. Results were surprisingly inconsistent - up and down by 20% (no idle boxes available) - but minimum times for both iterator and const_iterator were practically identical.

    I then got my compiler (GCC 4.5.2 -O3) to generate assembly output and visually compared the two loops: identical (except that the order of a couple register loads was reversed)

    iterator loop

        call    clock_gettime
        movl    56(%esp), %esi
        movl    $10, %ecx
        movl    60(%esp), %edx
        .p2align 4,,7
        .p2align 3
    .L35:
        cmpl    %esi, %edx
        je  .L33
        movl    %esi, %eax    .p2align 4,,7
        .p2align 3
    .L34:
        addl    (%eax), %ebx
        addl    $4, %eax
        cmpl    %eax, %edx
        jne .L34
    .L33:
        subl    $1, %ecx
        jne .L35
        leal    68(%esp), %edx
        movl    %edx, 4(%esp)
        leal    56(%esp), %esi
        movl    $1, (%esp)
    

    const_iterator loop:

        movl    60(%esp), %edx
        movl    $10, %ecx
        movl    56(%esp), %esi
        .p2align 4,,7
        .p2align 3
    .L38:
        cmpl    %esi, %edx
        je  .L36
        movl    %esi, %eax
        .p2align 4,,7
        .p2align 3
    .L37:
        addl    (%eax), %ebx
        addl    $4, %eax
        cmpl    %eax, %edx
        jne .L37
    .L36:
        subl    $1, %ecx
        jne .L38
        leal    68(%esp), %edx
        movl    %edx, 4(%esp)
        leal    56(%esp), %esi
        movl    $1, (%esp)
    

提交回复
热议问题