Skip to content

nativescript-websockets (Android): send() copies binary data one byte at a time across JNI, and sends the wrong bytes for a view into a larger buffer #26

Open

Description

@kjeib

@valor/nativescript-websockets 2.0.3 on Android: NativeBridge.send() in bridge.android.js has two problems with binary data.

send(data) {
  if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
    const byteBuffer = Array.create("byte", data.byteLength);
    const view = new Uint8Array(data instanceof ArrayBuffer ? data : data.buffer);
    for (let i = 0; i < view.length; i++) {
      byteBuffer[i] = view[i];
    }
    this.nativeWs.send(okio.ByteString.of(byteBuffer));

1. A view into a larger buffer sends the wrong bytes.

  • For a typed array, view is built over the whole underlying buffer, from offset 0. The view's byteOffset and byteLength are ignored.
  • So ws.send(bytes.subarray(10, 20)) sends bytes 0–9 of the buffer, not 10–19.
  • The loop also runs to the whole buffer's length while byteBuffer has only byteLength elements.
  • Libraries that send sub-arrays of pooled or concatenated buffers are exposed to this; libp2p's WebSocket transport sends Uint8Array chunks.

2. Every byte crosses from JS into Java separately. byteBuffer[i] = view[i] on a Java byte[] is one call into Java per element. Measured on a Galaxy S7 (Android 8, NativeScript 8.9, V8), per send, debug build, no inspector attached:

size per-element loop (current) okio.ByteString.of(arrayBuffer)
32 B 0.55 ms 0.49 ms
2 KB 17.3 ms 0.48 ms
16 KB 144 ms 0.50 ms

An Android emulator on an i9 shows the same shape: 60 ms against 2.3 ms at 16 KB.

Fix. A JS ArrayBuffer passed to a Java method taking a java.nio.ByteBuffer is marshalled in one call, and okio has ByteString.of(ByteBuffer). This fixes both problems:

send(data) {
  if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
    // The bytes of this view only, handed over in one call.
    const bytes = data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
    this.nativeWs.send(okio.ByteString.of(bytes));
    return;
  }

We have run this as a yarn patch: a libp2p node over a circuit relay on the S7 and the emulator, where every protocol message is binary.

Smaller, for consideration: receiving. A message arriving off the start thread is re-posted with a new java.lang.Runnable per message (scheduleToThread), and the thread is checked twice (android.os.Looper.myLooper()). At hundreds of small messages per second, queueing messages in JS and posting one reused Runnable that drains the queue in order saves a proxy object, a post and a thread check per message. We measured no clear end-to-end gain from that on the S7, so this is only a suggestion.

Activity

  1. kjeib commented on Oct 15, 2026

    @kjeib
    Author

    Correction: the fix suggested above leaks JNI global references. Please don't use it as written.

    Passing a JS ArrayBuffer to a Java method makes NativeScript create a java.nio.DirectByteBuffer and hold it with a JNI global reference until V8 garbage-collects the ArrayBuffer. At one send per message, a fast phone with plenty of memory collects rarely, so the references pile up. On a Galaxy S21 Ultra (Android 15, NativeScript 8.9.2) the app aborted after about 15 minutes of libp2p traffic:

    JNI ERROR (app bug): global reference table overflow (max=51200)
      50604 of java.nio.DirectByteBuffer (50604 unique instances)
    

    Reproduced directly: 60,000 calls of okio.ByteString.of(new Uint8Array(32).buffer.slice(0)) abort the same way. A slower phone (Galaxy S7) never reached the limit in our runs.

    A fix that creates no reference per send. Use one direct buffer and one JS view of it, made once and reused. Copy the bytes in with Uint8Array.set, set the buffer's limit, and let okio copy them out:

    let scratch = null;
    let scratchView = null;
    function scratchFor(size) {
      if (!scratch || scratch.capacity() < size) {
        let capacity = 65536;
        while (capacity < size) capacity *= 2;
        scratch = java.nio.ByteBuffer.allocateDirect(capacity);
        scratchView = new Uint8Array(ArrayBuffer.from(scratch));
      }
      return scratch;
    }
    
    // in send(data):
    if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
      const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
      const buffer = scratchFor(bytes.byteLength);
      scratchView.set(bytes, 0);
      buffer.clear();
      buffer.limit(bytes.byteLength);
      this.nativeWs.send(okio.ByteString.of(buffer)); // okio copies the remaining bytes, so the buffer can be reused at once
      return;
    }

    This still sends only the view's own bytes. On the S21, 120,000 such sends ran at 0.023 ms each with no growth in references. That is also faster than handing over a fresh ArrayBuffer (0.039 ms), and far faster than the per-byte loop (12 ms at 16 KB).

    The receive path's ArrayBuffer.from(data.asByteBuffer()) does not have this problem: asByteBuffer() returns a heap buffer, and 60,000 of those conversions left nothing behind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions