emscripten-core / emscripten

Emscripten: An LLVM-to-WebAssembly Compiler
Other
25.78k stars 3.3k forks source link

Question about life cycle of emscripten::val returned from temporary vector #16641

Open waterrhett opened 2 years ago

waterrhett commented 2 years ago

In C++, one can return temporary std::vector's like this:

std::vector<int> test() {
  std::vector<int> output = { 1, 2, 3 };
  return output;
}

and not have to worry about temporary vector being destructed afterwards, thanks to RVO or move semantics.

If I were to return emscripten::val in a similar manner, and coerce it into a TypedArray:

emscripten::val test() {
  std::vector<int> output = { 1, 2, 3 };
  return emscripten::val(typded_memory_view(output.size(), output.data()));
}

Can I still rest assured that the TypedArray I receive on JS won't be corrupted once the temp vector is destroyed? Is this handled in a similar manner (i.e. using RVO or move semantics) with emscripten::val?

waterrhett commented 2 years ago

It is not clear from the documentation, but judging from some discussions and examples I've been reading here... is this a better approach (assuming I'm returning Uint8Array)?

emscripten::val test() {
  std::vector<int> output = { 1, 2, 3 };

  emscripten::val memoryView{emscripten::typed_memory_view(output.size(), output.data())};
  emscripten::val jsTypedArray = emscripten::val::global("Uint8Array").new_(output.size());
  jsTypedArray.call<void>("set", memoryView);
  return jsTypedArray;
}
myseemylife commented 2 years ago

It is not clear from the documentation, but judging from some discussions and examples I've been reading here... is this a better approach (assuming I'm returning Uint8Array)?

emscripten::val test() {
  std::vector<int> output = { 1, 2, 3 };

  emscripten::val memoryView{emscripten::typed_memory_view(output.size(), output.data())};
  emscripten::val jsTypedArray = emscripten::val::global("Uint8Array").new_(output.size());
  jsTypedArray.call<void>("set", memoryView);
  return jsTypedArray;
}

hi~ how many times of buffer copy fires in test function? i found that the buffer in wasm exchange to js environment cost too heavy!Any ideas to improve the performance of exchange big data between js and wasm ?