Why are compilers so stupid?

前端 未结 29 1950
借酒劲吻你
借酒劲吻你 2020-11-29 18:07

I always wonder why compilers can\'t figure out simple things that are obvious to the human eye. They do lots of simple optimizations, but never something even a little bit

29条回答
  •  春和景丽
    2020-11-29 18:32

    On your first example, it's an optimization that only works if the value is zero. The extra if statement in the compiler needed to look for this one rarely-seen clause may just not be worth it (since it'll have to check for this on every single variable). Furthermore, what about this:

    int x = 1;
    int y = 1;
    int z = x - y;
    for (int i = 0; i < 100 * 1000 * 1000 * 1000; ++i) {
        z += z + z + z + z + z;
    }
    System.out.println(z);
    

    This is still obviously the same thing, but now there's an extra case we have to code for in the compiler. There's just an infinite amount of ways that it can end up being zero that aren't worth coding in for, and I guess you could say that if you're going to have one of them you'd might as well have them all.

    Some optimizations do take care of the second example you have posted, but I think I've seen it more in functional languages and not so much Java. The big thing that makes it hard in newer languages is monkey-patching. Now += can have a side-effect that means if we optimize it out, it's potentially wrong (e.g. adding functionality to += that prints out the current value will mean a different program altogether).

    But it comes down to the same thing all over again: there's just too many cases you'd have to look for to make sure no side effects are being performed that will potentially alter the final program's state.

    It's just easier to take an extra moment and make sure what you're writing is what you really want the computer to do. :)

提交回复
热议问题