Native calls have a lot of latency (Android)

Hello,

I am building a music app, where latency is critical, and I wanted to do the interface with Ionic and the audio engine natively.

I followed this tutorial for making a simple “echo” (JS → android → JS) and measured latency: I got from 20ms (ok) to 100ms, which is too much given that the audio engine will add some latency too.

Given that all return types are promises, I guess this is to be expected, but I wanted to make sure it is, and I would like to know if there is any workaround.

Interesting. I just did a quick test with my native audio plugin with calls to get the current time of the audio playing (makes a call every second). They are all under 10ms, average probably around 5ms.

Just used a simple Date.now calculation.

const start = Date.now()
const nativeCurrentTime = (
    await AudioPlayer.getCurrentTime({ audioId: internalAudioId })
).currentTime
console.log(`${Date.now() - start}`)

I tested on a physical Pixel 3 device in debug mode. I did notice if I interacted with the app like opening the audio controls which has an animation, the time would go up to 50-100ms. My guess this is because it’s on the same JS thread.

Can you provide some more details of how you are testing like the device you are using?

Thank you for these details.

I tested on a physical Pixel 8 in debug mode (USB), and I do the action on a button click:

async function click1() {
  const start = Date.now();
  const response = (await MyPlugin.echo({ value: "Hello" })).value;
  logger.info(`${response}, echo took ${Date.now() - start} ms`);
}

then with vuejs:

<button @click="click()">Button</button>

(this is a normal HTML button, but using ion-button doesn’t change anything)

Using this, I have an average response time of 30-40ms. If you want, I can give send you the whole repo in private messages.

I am just a Capacitor user and don’t know enough about the inter-workings of Capacitor to really help :smile: But, providing a sample repo would be useful for someone else to help.

I do know though as you eluded in the OP, no matter what, there is going to be some overhead using Capacitor as it has to serialize and deserialize the request and response between the JS and native land.

Out of curiosity, can you try putting MyPlugin.echo in a setInterval and see if you get the same result?

Yes, putting it in a setInterval led to the same result.

I put together a toy project showcasing this, sadly I can’t upload a zip file here (even though it is less than 1MB), so there you go: https://file.io/GzX8hvWVpMYI

In case you don’t want to bother downloading and opening it: it’s really just a new Ionic project with the android java files copied from the tutorial in the original post

you should just create this project in stackblitz. it would be a lot easier.