A
A
Alexey2021-06-24 00:24:49
JavaScript
Alexey, 2021-06-24 00:24:49

JSON parsing in worker?

Of the answers only from 2015 in Google.
Does it make sense to make a separate websocket worker? I communicate with the server by spitting JSON on it.
The question is: is parsing jsona in a separate thread leveled due to copying objects when passing from the worker and back? Or is there such a design?

// App.vue
mounted() {
  this.$store.state.socketWorker = new Worker('/js/socketWorker.js');
  this.$store.state.socketWorker.addEventListener('message', ({ data }) => !this.$store._mutations[data.a] || this.$store.commit(data.a, data)); 
};


// Воркер
var ws = new WebSocket('wss://someaddr');

ws.onmessage = ({data}) => {
  try { data = JSON.parse(data); } catch(e) { return; };
  self.postMessage(data);
};

self.addEventListener('message', ({ data }) => {
  if (!ws || ws.readyState !== 1) return;
  let msg = '';
  try { msg = JSON.stringify(data); } catch(e) { return; };
  ws.send(msg);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-06-24
@Azperin

I would prefer the department in favor of no worker. This approach only works if you have very large JSONs. So large or so many that the time to process them is noticeable to the naked eye.
If this is not the case, then it would be more convenient for me to keep the socket in the main thread. This will enable all components to independently subscribe to different events. Something like this:

// socketFactory.js
let ws = null

export function getSocket() {
  if (!ws) ws = new WebSocket('wss://someaddr');
  return ws
}

// SomeComponent.vue
import {getSocket} from 'socketFactory.js'
const ws = getSocket()

export default defineComponent({
  created() {
    ws.onmessage(message => {
      if ( ... ) {
        // Делаем что-то с сообщением
        this.onMessageHandled(message)
      }
    })
  },
})

Thus, each component can communicate with the socket independently. This eliminates the need for Vuex. My example is far from ideal, it would be worth bringing the socket to another layer of abstraction, but I hope you understand the idea.
And I emphasize that all this can be harmful, since I do not know your entire architecture.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question