Question

I know it probably wouldn't make much sense to do it as usually it's faster and more logical to just rewrite performance-critical sections in a faster language, but setting that aside, is it possible to write faster CPython/JVM/CLR programs by writing portions directly in their assembly?

Was it helpful?

Solution

Actually, it is. Not often mind you, but I know of at least one case (skipping the and in MSIL makes that code a tiny bit faster). There are probably more cases, the CLR JIT compiler isn't all that smart.

OTHER TIPS

No, it is not recommended. For example, the Just-In-Time compilation feature in some JVMs searches for bytecode patterns to optimise them significantly at runtime. If you substitute them with your own twisted bytecode, JIT might not work and you will end up with a slower code. This is what happens sometimes when you obfuscate Java programs.

No. The bytecode for most high level languages is very high level, and usually corresponds well with that idioms that language uses - you simply can't write the code to do a simple task any way other than what the compiler already emits, at least not without making it slower.

Most speedup from hand crafted assembler comes from clever register usage, clever use of machine specific opcodes, etc - all things you have no control over when writing high level bytecode.

Also it's important to note that if you emit unusual code - say in some stack-based vm you notice a value is used twice, and being clever rather than emitting a temporary variable you leave it on the stack and dupe it later.. you've possibly just hit performance hard. The JIT no longer recognises the idiom, and emits awful code as a result. I've been hit by this firsthand emitting runtime generated MSIL - if what you're emitting doesn't resemble compiler generated code, it's probably not going to perform.

Of course I'm talking about MSIL here specifically - but I believe in general it will hold true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top