Not sure this is an android issue, I am a c++ developer trying to write java 🙂
The problem in brief..
I have replaced a long and hard to maintain switch case with
a finite state machine and while the base code is the same I get
about 20% performance loss
Some more detailed explanation:
I’ve create a SurfaceView based andriod app based on the sample code from SDK
after extending my app I found myself maintaining long switch cases on my game loop
generally my app skeleton looks like this (with many cases)
class myView extends SurfaceView implements SurfaceHolder.Callback {
public void update() {
switch (_state) {
case MENU: ... break;
case LOAD: ... break;
case RUN: ... break;
...
}
}
public void draw(Canvas c) {
switch (_state) {
case MENU: ... break;
case LOAD: ... break;
case RUN: ... break;
...
}
}
public boolean onTouchEvent(MotionEvent event) {
switch (_state) {
case MENU: ... break;
case LOAD: ... break;
case RUN: ... break;
...
}
}
}
So I decided to refactor my code and implemented a simple finite state machine (FSM)
public class StateMachine {
public State state;
private myView context;
public StateMachine(myView view) {
context = view;
state = new StateMainMenu();
}
interface State {
public void update();
public void draw(Canvas canvas);
public boolean onTouchEvent(MotionEvent event);
}
class StateMainMenu implements State {
public StateMainMenu() { ... }
@Override
public void update() {
...
if (windOfChange) {
state = new StateTheNextState();
}
}
@Override
public void draw(Canvas canvas) { ... }
@Override
public boolean onTouchEvent(MotionEvent event) {
synchronized (_thread.getSurfaceHolder()) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: ... break;
...
}
return true;
}
}
}
}
and in myView is used it like this
class myView extends SurfaceView implements SurfaceHolder.Callback {
private StateMachine stateMachine = new StateMachine(this);
public void update() {
stateMachine.state.update();
}
public void draw(Canvas c) {
stateMachine.state.draw(c);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
synchronized (_thread.getSurfaceHolder()) {
return stateMachine.state.onTouchEvent(event);
}
}
}
While, inside the states I do exactly what I did before
same amount of objects creations and the very same code
running my app I get about 20% less frame rates…
Any ideas why? or what am I doing wrong?
My advice would be to profile your app’s execution with Traceview to identify which part of it is acting as a bottleneck. Without that, it’s a bit like shooting in the dark.
I would put my 2 cents on the synchronized blocks though.