Android port of JBox2D testbed

Like most, I've noticed that the largest enemy to smooth Android game is the garbage collector. I've been looking at ways to cut down the amount of object allocations done during the average 'step' operation in JBox2D. I have a few ideas, and I was wondering what other people thought.

1) I've noticed the evaluate method in the Contact Objects ( like org.jbox2d.dynamics.contacts.CircleContact ) generates several objects every cycle.
Essentially a contact point and a manifold are generated and then passed to a ContactListener, (if it is defined). I think this area would still work if those objects where generated once along with the parent Contact object and used over and over again. The only problem with this would be that the user callback would be receiving a 'borrowed' object, that it would have to copy before playing with.
Also, change the

Code: Select all

cp.normal = m_manifold.normal.clone();

to

Code: Select all

cp.normal.set( m_manifold.normal )


2) The World object creates two island objects (one in solve and one in solveTOI). Rather then re-creating them every step, create them once, keep them as private objects and add a method Update to Island.

Code: Select all

public Update(int bodyCapacity,
               int contactCapacity,
               int jointCapacity,
               ContactListener listener) {
       
       m_bodyCapacity = bodyCapacity;
       m_contactCapacity = contactCapacity;
       m_jointCapacity    = jointCapacity;
       m_bodyCount = 0;
       m_contactCount = 0;
       m_jointCount = 0;

       m_listener = listener;
   
   if ( m_bodies.length < bodyCapacity )
          m_bodies = new Body[bodyCapacity];
   if ( m_contacts.length < contactCapacity )
          m_contacts = new Contact[contactCapacity];
   if ( m_joints.length < jointCapacity )
          m_joints = new Joint[jointCapacity];
       m_positionIterationCount = 0;
    }


This would only re-allocate the arrays when they needed to get bigger.


3) Create a 'pool manager' that keeps references to frequently generated objects, and recycles them rather then allowing the garbage collector to get to them:

Code: Select all

import java.util.LinkedList;

public abstract class MemoryPool<T> {
   private LinkedList<T> free_items = new LinkedList<T>();      
   public void freeItem(T item) {
      free_items.add(item);
   }   
   public abstract T Allocate();   
   public T newItem() {
      T out = null;      
      if ( free_items.size() == 0 ) {
         out = Allocate();         
      } else {
         out = free_items.getFirst();
         free_items.removeFirst();
      }
      return out;
   }      
}
Hi guys, thanks a lot for the porting effort of box2d for Android. As many, I have tried yesterday doing a simple app and was quickly noticing the garbage collection problem, which is an android-wide problem itself not only in box2d.

When do you think that a usable version of the library will be available? I am not too keen on doing work on the porting myself but I can try to help if you guys think it would be useful to have a box2d noob onboard.

Another question, what is the current status of JJC1138's patch with regards to garbage collection?

/edit I just tried using the lib-only jar from the svn trunk branch and there is quite a lot of garbage collection (like 250ms every second). Does this library include the recent optimizations?
Another question, what is the current status of JJC1138's patch with regards to garbage collection?


It looks like those changes were added in revision 142. http://jbox2d.svn.sourceforge.net/viewvc/jbox2d?view=rev&revision=142. But there is still a lot more that would need to be changed in order to get to a zero allocation 'step'. You can help by tracking you Android app with 'ddms' and locating the areas that seem to be doing the most allocations during the 'step'.


Some of the things we can do to combat the problem:

1) Inline all math : This would speed things up (eliminate method calls and remove excess Vec2/Mat22 allocations), but it would make the code a mess...

2) Create memory pools for frequently allocated&deallocated items: By recycling items like arbiters/manifolds/vec2/mat22 we avoid letting the garbage collector get to them. However this would require adding manual 'delete' like statements to manually keep track of when objects can be added back into the recycle pool. If an item was recycled to early (with another reference to the object being used somewhere else) side effects would be random...

3) Pass listener functions borrowed references: Right now collisions generate several new objects every step and pass them to listener functions. If the listener function is just reading values, a borrowed reference to member of the collision object would work just as well. However if the listener function was to write to the passed object it may produce unexpected results....
Before you spend a significant amount of time optimizing to reduce GCs, I would encourage you to build a quick test that has a similar amount of objects to the app you're planning to build and test that on a device. When I did that I found that the app I had in mind was simply too slow to be workable because of the lack of FPU in current Android devices.
JJC1138 wrote:Before you spend a significant amount of time optimizing to reduce GCs, I would encourage you to build a quick test that has a similar amount of objects to the app you're planning to build and test that on a device. When I did that I found that the app I had in mind was simply too slow to be workable because of the lack of FPU in current Android devices.

I'm aiming pretty low for right now, my project has very few objects, just circles and polys, no springs or joints. It seems to run at a decent rate most of the time (on the actual hardware, the emulator is slower). But there is a noticeable 'pop' every few seconds when the garbage collector hits.
Well, it looks like the Native Development Kit is out, http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html. Anybody play around with it yet?
You might want to know, the current svn version of JBox2D is substantially faster and object creations have been reduced by half or more. What are the main limitations for the Android environment? Is there any changes that should be considered for JBox2D to make it run better on phones?
toucansam wrote:You might want to know, the current svn version of JBox2D is substantially faster and object creations have been reduced by half or more. What are the main limitations for the Android environment? Is there any changes that should be considered for JBox2D to make it run better on phones?


I've been keeping up with the SVN. I'm glad to see the improvements in the code. The problem is that with android, the dalvik garbage collector is a big hiderence. In practice, when using JBox2D, it will lock out your program for 300 microseconds, or about a third of a second in very regular intervals. Bascially it will give your game a stager. http://android-developers.blogspot.com/2009/02/track-memory-allocations.html.

The calculation step has to have zero allocations to really avoid this problem. Even variables passed from JBox2D to user listener functions would have to be recycled.

Alternatively, we could implement a simple JNI interface to the C++ version, compile that with the new Android NDK. All the memory handling would be done in C++, and the dalvik garbage collector wouldn't freak out.

Kyle
kellrott wrote:In practice, when using JBox2D, it will lock out your program for 300 microseconds, or about a third of a second in very regular intervals. .... The calculation step has to have zero allocations to really avoid this problem. Even variables passed from JBox2D to user listener functions would have to be recycled.


As I'm updating the engine, I'm very concious of pooling all object creations, even the ones passed to listener functions. My goal (which I know I probably won't achieve) is to have 0 allocations per frame step. I'm starting with pooling math objects, but later I'll probably keep a stack of temporary objects for contact points, etc, so everything is reused. Should take some time though 🙂


kellrott wrote:Alternatively, we could implement a simple JNI interface to the C++ version, compile that with the new Android NDK. All the memory handling would be done in C++, and the dalvik garbage collector wouldn't freak out.


That's probably your better option. I'm not sure if anyone is working on that kind of port, however.
Hi guys,

besides doing a native port and interfacing it, there will be a significant performance boost if using the "FloatMath" class instead of the 'normal' Math class on Android. Those methods (sin, cos, sqrt, ...) run about 3x faster than the double-versions from java.util.Math.
Up to now I had no time to look at the code, but I assume that a Physics-Library uses Math-functions quite often 🤓

Another optimization that could be done is using less 'genericism', like preferring:

HashMap<X,Y> map = new HashMap<X,Y>();
over
Map<X,Y> map = new HashMap<X,Y>();

Just my thoughts 😉

[Edit]Ok, having looked at it for some moments, there is a lot that could be optimized...
I'd love to participate, as I have a kind of Android-knowledge 😉 (I'm running http://anddev.org and http://andnav.org )
But I do not know how smart it is to fork an Android-Version of JBox2d which itself is forked from Box2d ➡️ ❓

Let me know what you think... 🙂
[/Edit]

Regards,
Nicolas

Original thread: https://box2d.org/forum/viewtopic.php?t=2794