Optimizing y-websocket CPU use

I was surprised to hear my Macbook Pro fan speeding up when using y-websocket, so I looked at the CPU to find that with two Firefox windows open, y-websocket was using about 33% of a CPU each:

I pared my program down until there was nearly nothing left, and was surprised again to find out that simply creating a WebsocketProvider is what causes this overhead:

import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'

const doc = window.doc = new Y.Doc()
const state = {
  global: doc.getMap('global'),
  presence: doc.getMap('presence'),
}

const wsProvider = new WebsocketProvider('ws://localhost:1235', 'ayanarra', doc)

Am I mis-using this in some way? Is this type of CPU load expected?

Thanks!

No, this is definitely not to be expected!

Could you please also inspect using the performance panel in Firefox? Open DevTools ⇒ Performance ⇒ start recording and share the activity.

Does the same issue happen on https://demos.yjs.dev/prosemirror/prosemirror.html ?

The same issue does not appear to happen on the prosemirror link you provided.

I profiled the code and it appears the problem may be with the setInterval call (still investigating). I wonder if calling setInterval with no delay is “undefined behavior” for browsers?

I’m more confident now that it’s the setInterval that is causing the issue. Here is the Waterfall view of the performance results:

Here is the Call Tree:

Although it appears not to be taking significant time in the Call Tree, I’ve verified that it is consistently the case that the system Activity Monitor reports a 30% increase in activity on one “FirefoxCP Web Content” process per window that has my y-websocket app open.

Adding a 500 millisecond delay to setInterval brings that CPU activity down to about 5%, which seems much more reasonable.

1 Like

Thats interesting, and some great profiling. A sometimes also had the feeling that a lot of resources are used in my tests.
Is there a PR for this already to test?

Yes, see https://github.com/yjs/y-websocket/pull/13

1 Like

Thanks @canadaduane for profiling and fixing the issue! I published a new release with your fix y-websocket@1.2.5.

1 Like