
Rust Optimizations That C++ Can't Do (Version 2) - nachtigall
http://robert.ocallahan.org/2017/04/rust-optimizations-that-c-cant-do_5.html
======
lorenzhs
Note that if you're very explicit about _v_ not changing in the C++ code, like
so:

    
    
        const long w = v;
        for (int i = 0; i < 100; ++i) {
          sum += w;
          callback();
        }
    

...then clang++ generates the following:

    
    
        .LBB0_1:
            call    rbx
            dec     ebp
            jne     .LBB0_1
            imul    rax, r14, 100
    

It optimised away all of the additions, calling _callback_ in a loop and then
multiplying _w_ with 100. This is something the rust compiler doesn't
currently do.

What this boils down to is that there isn't a good way of telling the compiler
that the content of a reference _will never change_ in C++. As noted in the
other thread
([https://news.ycombinator.com/item?id=14040021](https://news.ycombinator.com/item?id=14040021)),
_const_ says that the current context can't change it, but someone else might
still be able to.

