4 ms·
I feel like this is something the compiler could do automatically. Give it a hint, let it do some alias analysis and discover that a particular variable won't c
by kccqzy 8y ago
I feel like this is something the compiler could do automatically. Give it a hint, let it do some alias analysis and discover that a particular variable won't change throughout a loop. And then let it treat that variable as a constant (as an immediate in instructions) and generate the code to modify it at the beginning. Perhaps let it pass on this information so that eventually the section could be mapped W+X.
- kragen 8y agoSelf-modifying code to optimize a hot loop is only a useful thing to do on a machine without a split I/D level-1 cache. All modern high-performance CPUs will suffer an instruction cache flush on each iteration of the hot loop, which will kill your performance. Also, though, even on CPUs with no instruction cache, it's probably a very minor improvement at best. Suppose you write the variable in one place and read it in 4 places. If no register is allocated to the variable, on a load-store machine such as a RISC, the usual approach involves one store and four loads. But if you use self-modifying code instead, you have four stores (and no loads), but those stores are modifying only part of an instruction word — so, on most hardware, they actually require a preceding load, even if the architecture tries to hide that from you. I'm convinced there are cases where this kind of optimization actually speeds up your code, but they are pretty unusual.