Programming Tips

Wednesday, August 29, 2007 Labels:

Well, if you’re serious about making J2ME games, you’ve probably heard this one before, but I guess it doesn’t hurt to repeat it. You can’t use the standard object oriented java approach using a lot of classes, inheritance, getters and setters. You need to fit everything into just a few Java classes. Two or maybe three classes, that’s what you have to work with.

There are several reasons for this. Memory consumption is one thing, there is some memory overhead every time you create a new object from a class and so forth. Speed is another, on the low level side of it, true object oriented java creates more bytecode opcode instructions and more instructions take a longer time to execute.

But the main issue is size. And it has more to do with java midlet packaging in jar files than the structure of java bytecode, really. Midlet jar-files are compressed using the zip deflate algorithm, and deflate compresses files individually. Two separate files always get better compressed if you join them to one file. Basically, this is because the deflate algorithm gets more data to work with. So if you think about this, your jar file will compress better if you gather your code into a few java class files instead of having your code spread out in lots of smaller class files. The approach to join data into bigger data pack files to get better compression can be used for your game data (images, level data etc) as well.

So, two classes is basically what you need. One MIDlet class and one Canvas class. The canvas class can implement the Runnable interface so you can use it to run an update thread for your game animation.

Some other basic tips:

  • Use switch-case blocks instead of if-blocks as much as you can. Switch case blocks gets translated in to java bytecode “jump tables” when compiled that uses less instructions and runs faster. This is good for speed optimization, especially in your inner loops.

  • Access public variables directly instead of using get and set functions. This looks like bad programming, but it’s actually faster and uses less bytecode instructions.

  • Use local instead of global variables when you can. Using local variables is faster and uses less bytecode instructions.

  • Don’t forget to free memory by setting your objects to null when you don’t need them anymore. The garbage collector will take care of it when it gets a chance. If you want to be sure the garbage collector runs (after an initialization routine for example) you can always use the System.gc(); function to activate it.

  • Another very basic but still good tip is to always declare your constants to “final static”. The declarations are still going to be compiled into your java class file, but they get removed if you use a good bytecode optimizer such as Proguard.


Post a Comment

Waqas Sadiq © 2014