Sign in to follow this  
Sagar_Indurkhya

Optimizing Java Bytecode

Recommended Posts

I'm in the process of practicing for a competition by writing several complicated algorithms in java. Part of the goal is to minimize the total number of bytecode instructions that the JVM executes (and each round I'm allowed to use up to a limit between 1,000 and 10,000 bytecodes). My main focus is on writing the algorithms cleverly, but since at some points in my application I'm looping, I figure that even small unnecessary things will eat up lots of bytecodes if I'm not weary. Also it intrigues me. :) One thing I have kept in mind is that even if my algorithm when compiled into java bytecode might take up 50,000 bytecode instructions, but if a lot of it is branching etc, then I can still get away with not executing most of them. Any tips and pointers? I've never really thought about optimizing at bytecode level in Java (since the emphasis in Java seems to be that you DON"T want to be doing this level of optimization, but it's the nature of competition).

Share this post


Link to post
Share on other sites
Here's a few thoughts off the top of my head to get you started, some are simpler to do than others, and you'll need to test them to be sure you get savings as I haven't!

- Firstly pick the right algorithms. Avoid bubblesort, etc. That will make a huge difference.
- Familiarize yourself with javap so you get an idea of what source creates what bytecodes. Compare different ways of doing the same thing like say switch vs if.
- Use an optimizing java compiler "javac -O" is the standard way of turning them on, but you may be able to find a better compiler as the standard one isn't very good at optimizing. Hand optimizations are also a good idea.
- Don't put too many conditional checks in - check to see if doing the test is cheaper than the work it avoids, and that the test avoids that work frequently.
- Make everything static. It's an extra bytecode or two to access if not.
- Function calls are overhead, and last I looked the compiler didn't inline very well. Put all your code in one function if you can.
- Don't use container classes if you don't need them. They will add overhead.
- In fact also avoid all function calls that you can.
- I have a feeling static member variables will also add overhead compared to locals, but test it.
- Some JVMs will execute some standard functions (e.g. Math.min()) without using bytecodes, find those and use them if you know the target JVM.
- The first four numeric variables or arguments in a method are accessed via fewer bytecode instructions.
- Use "a += b;" instead of "a = a + b;" etc.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this