Can I optimize the vector3f calculations?


I’m making a gravity based space game for android.

When I was debugging on desire z I had no problems with lag. The game ran as smooth as a babys behind :slight_smile:

But now I’m using another cell, and it lags quit much.

I’v tried to reduce it by:

-Removing textures

-Not calculating the physics for each fps.

The second alternative worked great. Tho it also implies that the physics takes too much cpu.

I think it’s because when doing an operation on a vector3f, it will return a whole new vector.

I think this waste of vectors will lead to the cpu sucking. So I would need input on how to avoid that.

Here is how I calculate the physic for my rocket:

[java]public void updatePhysics(float tpf, ArrayList<PhysicBody> list) {

if (remove){


} else {

this.gravity = Vector3f.ZERO;

for (PhysicBody body : list) {

Vector3f attraction = body.getPosition().subtract(this.position);

if (body.canCollide() && body.getPosition().distance(this.position) < body.radius){

this.remove = true;

} else {

float r2 = attraction.lengthSquared();

attraction = attraction.normalize();

float a = body.weight / r2;

attraction = attraction.mult(a);

this.gravity = this.gravity.add(attraction);

//this.velocity = this.velocity.add(attraction);



float res = PhysicManager.G*tpf;

this.gravity = this.gravity.mult(res);





And running this on a map whereas theres just two other objects but the rocket, and only the rocket calculate the physics meens this is cpu consuming.

As you see I’v tried to take out some properties from the actual ekvation and adding them at the end. But this is still slow.

Any suggestions?

What do you mean by lag? Are there pauses where the animation halts, or is the game running behind its input?

If it’s the former, then you’re on the right track by looking at memory allocation. In your example above, yes, it’s allocating an extra vector in the subtract operation. You can get around that by using the Local versions of the vector math operations – those don’t allocate a new vector, but operate in-place on an instance passed in. I don’t know what your physics is doing and I haven’t worked with it in JME, but I’d be surprised if the problem weren’t mostly memory thrashing and not raw CPU usage.

Look for anything else that’s allocating memory during your application’s rendering loop – garbage collection will kill you on Android. The allocation tracker tool in the ADK will really help you with that. There are a few allocations in JME’s rendering loop that are on my list to track down, but it’s not too bad. If you’ve got all the memory allocations stomped out and it’s still slow, the ADK has a CPU profiling tool that can help. Like any profiler, it has its own quirks that you need to learn, but it can be pretty useful.


sbarta THANK YOU!

All these years I never understood what the local ment. Using it now really improved my fps! :slight_smile:

Thanks :slight_smile: