upvote
At least in JVM land, it's pretty easy to thwart that optimization. Particularly if the condition is on a mutable yet unchanged in the loop value.

For example:

    var map = new HashMap<String, String>();
    map.put("foo", "bar");
    for (var i : items) {
      if ("bar".equals(map.get("foo")) {
        doStuff(i);
      }
    }
Even though `map` isn't mutated, it's hard enough for the JVM to detect and the underlying `get` functions are complex enough that it'll run the `get("foo")` every time, which can be quite expensive.
reply
Can't speak for C# but in C/C++ the optimization can rarely be applied safely due to aliasing. If any part of the data you're working with involves a char* then C/C++ optimizers refrain from doing these kinds of optimizations because of how difficult it is to guarantee the absence of mutability.
reply