With regard to the sufficiently smart compiler: it seems like you'd need every method the StringBuffer is passed to be final to do that kind of analysis.
In the case where you're writing:
public void foo(List<String> strings) {
StringBuffer x = new StringBuffer();
for (String s: strings) {
x.append(s);
}
}
You could conceivably do the analysis at compile time. But the whole idea behind the JIT is that you don't need to. If the code is hot, it'll get compiled, and you'll probably be fine thanks to removing all the synchronization, while if it's not hot no one cares.I wish C++ had a runtime that could do same, inline smaller virtual methods, function pointers and shared library (.dll/.dylib/.so) calls at runtime.
It could also do other transformations, like optimize those branches away it can prove to be always true or false. It could flatten most abstractions, removing redundant parameter checks and call frame setups/teardowns. It could also do CPU (instruction set) specific optimizations.
I think C++ runtime that does this partial JITting is possible, but not easy. However, the benefits are interesting. While getting there won't be easy, you can achieve faster than native performance.
Something like this has already been actually done. Some examples below.
QuaC: http://digitalassets.lib.berkeley.edu/techreports/ucb/text/C...
DynamoRio: DynamoRio had some early success JITting native binaries resulting faster than native performance. Unfortunately current versions are slower than native.
https://github.com/DynamoRIO/dynamorio).
https://dspace.mit.edu/bitstream/handle/1721.1/87441/5486358...
Actually, I don't see why it would take a very smart compiler to do this kind of escape analysis and automatically and safely replace StringBuffer by StringBuilder where possible. The only large downside I can see of that is that it would require the compiler to know quite a bit of the semantics of the standard library.
If you refactor your code and pass the StringBuffer to (small) helper functions, doing this would be more work, but it would not get essentially harder.