4

I'm trying to do some processing with webworker on image data from canvas. Solution, that I have right know, works quite ok, but there are still some visible lags when I do the processing (because besides processing I have to draw video from webcam to canvas and it starts to lag).

So I tried to use webworker and I did everything asynchronously. The only problem is that when I use JSON.stringify, it takes longer than actual processing.

My question: is there any other way, how to pass lot of data via worker.postMessage quickly? Is there some kind of workaround that I don't know about?

Small subquestion: what for are webworkers? I find workers really useless, passing just strings.

EDIT:

possible duplicate: Pass large amounts of data between web worker and main thread

Community
  • 1
  • 1
sjudǝʊ
  • 1,565
  • 1
  • 23
  • 34

1 Answers1

3

Everything is copied to a webworker, so unless your computation is very intensive, I doubt you'll see much gain there.

WebWorkers are meant for long-running, computationally intensive algorithms. The obvious use cases are:

  • AI in web games
  • Raytracers
  • Compression/decompression on large data sets
  • AJAX requests that need a lot of processing before it's displayed
  • Other complex algorithms

Since data is copied both ways, you have to be careful about what you're doing. WebWorkers don't have access to the DOM, so they're likely useless for what you're trying to do. I don't know what your app does, but it sounds like it isn't very intense.

There are also Sharedworkers, which can be shared by multiple tabs/windows, which is a really nice way to pass data between tabs.

Edit:

Also look into the structured clone algorithm. It seems to be more efficient that JSON for many things, and can even duplicate ImageData (so it doesn't just support strings anymore).

For browsers that don't support the clone algorithm, I would urge you to consider base64. It's decent at storing binary data, and I think it's faster than JSON.stringify. You may have to write some code to handle it though.

beatgammit
  • 19,817
  • 19
  • 86
  • 129
  • I'll take a look at that structured clone algorithm and see if I can get some speed improvement. Btw. what I'm doing in app is that I take frame from webcam (every second) and do some image processing like face recognition, position of subject and so on. Later I'm going to add more and more stuff (maybe) and I'm already preparing for that, it might take longer and longer. And since I need to keep drawing frames to canvas, worker seemed like reasonable solution. Or, I'll just stick with what I have and optimise, optimise, optimise... – sjudǝʊ Dec 05 '12 at 22:44
  • Yeah, the structured clone algorithm will probably help out a ton. I assume you are only sending metadata back from the web worker (not a whole image)? – beatgammit Dec 06 '12 at 02:25
  • Sure, just few result values. – sjudǝʊ Dec 06 '12 at 07:07