What is more productive in the OpenGL renderer loop: "if" operator or lambda?

alexrnov :

When the rendering of the game is started, part of the algorithm changes (handling of the click on the screen).

There are two options. 1. Use the "if" operator:

public class Leve1 implements GLSurfaceView.Renderer {
  private boolean isLoadGame = false;
  public void onSurfaceChanged(GL10 glUnused, int width, int height) {
    ...
    isLoadGame = true; // game is now loaded
  }
  // this method is called often in the render loop
  public void setPassXY(float x, float y) {
    if (isLoadGame) {
      ... // perform algorithm 
    }
  }
}

2. Use the lambda (without "if"):

public class Leve1 implements GLSurfaceView.Renderer {
  // when the game is not loaded yet use the empty method body
  private PressXYInterface<Float, Float> pressXY = (pressX, pressY) -> {};
  public void onSurfaceChanged(GL10 glUnused, int width, int height) {
    ...
    pressXY = (passX, passY) -> { 
      ... // game is now loaded - add algorithm
    };
  }
  // this method is called often in the render loop
  public void setPassXY(float x, float y) {
    pressXY.invoke(x, y); // perform algorithm
  }
}

@FunctionalInterface
public interface PressXYInterface<T, U> {
  void invoke(T x, U y);
}

Question: which approach is better to use in terms of performance?

Stephen C :

I don't think there can be a single correct answer. It depends.

On the one hand, the version using lambdas saves an if statement.

On the other hand, the version using the method call can potentially be inlined by the JIT compiler. (The lambda call cannot be inlined because at different points the application will / may be calling different lambdas.)

On the other hand, if // perform algorithm is complicated enough, it will be too big to inline.

On the other hand, if the algorithm is too big to inline, perhaps the cost of the if test will be insignificant.

On the other hand, the if test may be less expensive than you imagine. For example:

  • If the code JIT compiled only after running in isLoadGame == true state, then the stats may tell it bias the code for the case where the the test succeeds.
  • (Hardware) branch prediction may affect the performance.

On the other hand, it is not clear to me either or both versions need to make simple calls or virtual calls. And whether the JIT compiler could optimize the virtual calls. I simply don't know.

Then there are the issues of different JIT compiler versions, different hardware ISA, different hardware implementations.

In short, there are too many factors to predict which approach will be faster.

Benchmarking your real application is the only way to get a reliable answer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=22081&siteId=1