4 ms·
A good compiler can in a large number of cases infer that it won't modify. The compiler can explore the call graph of the loop body and find out which methods
by mpartel 7y ago
A good compiler can in a large number of cases infer that it won't modify.
The compiler can explore the call graph of the loop body and find out which methods might be called on the list, and then check that none of those methods write to the list's internal length variable.
How deeply and precisely the compiler (or JIT) analyzes the code in an attept to prove that the length won't change involves a tradeoff in compilation speed, but I'd expect .NET to have found a pretty good sweet spot by now.
- josteink 7y ago> A good compiler can in a large number of cases infer that it won't modify. For a single thread that should be doable. But that’s not mathematically covering all bases is it? And how can the compiler know if the relevant list is not accessed from multiple threads? I’m pretty sure that’s next to impossible and definitely not worth the complexity for such a small optimisation.
- sreque 7y agoCompilers have been assuming single-threaded memory access by default since, forever? If you want your code to work with multiple threads, then you have to explicitly write code to do so. Otherwise, the compiler is liable to store things in registers, shuffle instructions around, and do whatever it feels like to optimize performance for the single-threaded case. If the compiler didn't do this, then every program would run many many times slower than it does. Doing some quick googling, this article seems to explain things well from the perspective of a C# developer: https://afana.me/archive/2015/07/10/memory-barriers-in-dot-net.aspx/ https://afana.me/archive/2015/07/10/memory-barriers-in-dot-n...
- Someone 7y agoIt often is easy to know it isn’t accessed elsewhere (escape analysis can prove it for local variables), and compilers do check the simple cases (search term: “lock elison”). For example, see https://shipilev.net/jvm/anatomy-quarks/19-lock-elision/ https://shipilev.net/jvm/anatomy-quarks/19-lock-elision/. This also can help when using java’s StringBuffer, which is thread-safe, but can often be ‘converted’ into a non-thread-safe variant by the compiler (the existence of StringBuilder shows that ‘often’ at least in some version of Java wasn’t often enough, though)