From 1711a00c0d23dfd2fb25e6b419b808716cd30007 Mon Sep 17 00:00:00 2001 From: simonla Date: Fri, 19 Aug 2022 02:45:47 +0800 Subject: [PATCH] Avoid object creation during each frame (flutter/engine#35343) --- .../android/io/flutter/view/VsyncWaiter.java | 44 ++++++++++++++----- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java b/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java index c5021460da8..80f5658dea5 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/VsyncWaiter.java @@ -47,6 +47,7 @@ public class VsyncWaiter { private static DisplayListener listener; private long refreshPeriodNanos = -1; private FlutterJNI flutterJNI; + private FrameCallback frameCallback = new FrameCallback(0); @NonNull public static VsyncWaiter getInstance(float fps, @NonNull FlutterJNI flutterJNI) { @@ -85,22 +86,41 @@ public class VsyncWaiter { listener = null; } + private class FrameCallback implements Choreographer.FrameCallback { + + private long cookie; + + FrameCallback(long cookie) { + this.cookie = cookie; + } + + @Override + public void doFrame(long frameTimeNanos) { + long delay = System.nanoTime() - frameTimeNanos; + if (delay < 0) { + delay = 0; + } + flutterJNI.onVsync(delay, refreshPeriodNanos, cookie); + frameCallback = this; + } + } + private final FlutterJNI.AsyncWaitForVsyncDelegate asyncWaitForVsyncDelegate = new FlutterJNI.AsyncWaitForVsyncDelegate() { + + private Choreographer.FrameCallback obtainFrameCallback(final long cookie) { + if (frameCallback != null) { + frameCallback.cookie = cookie; + FrameCallback ret = frameCallback; + frameCallback = null; + return ret; + } + return new FrameCallback(cookie); + } + @Override public void asyncWaitForVsync(long cookie) { - Choreographer.getInstance() - .postFrameCallback( - new Choreographer.FrameCallback() { - @Override - public void doFrame(long frameTimeNanos) { - long delay = System.nanoTime() - frameTimeNanos; - if (delay < 0) { - delay = 0; - } - flutterJNI.onVsync(delay, refreshPeriodNanos, cookie); - } - }); + Choreographer.getInstance().postFrameCallback(obtainFrameCallback(cookie)); } };