How can I free memory allocated by Rust code exposed in WebAssembly?

后端 未结 2 2045
温柔的废话
温柔的废话 2021-02-19 08:09

I have a web application written in Rust and wasm-bindgen that needs to store state. The state is stored like this:

lazy_static! {
    static ref ID_TO_DATA: Mut         


        
相关标签:
2条回答
  • 2021-02-19 08:48

    My visitors spend hours on my website without reloading it.

    My wasm program runs once every 5 minutes, for 0.5 seconds each time. It is called by a synchronous JS function, which expects the output right after the wasm finishes. During the execution, the wasm program needs 700 MB of RAM.

    I would like to release these 700 MB when the wasm program does not run. What JS object should I release (remove references to)? Next time my JS function runs, I want to run the wasm program again (in a synchronous way).

    I was thinking about recompiling WASM each time my JS function runs, but all current browsers compine WASM asynchronously. Is there anything else I can do?

    These lines do nothing:

    wasm.instance.exports.memory.buffer = new ArrayBuffer(10);
    wasm.instance.exports.memory = new WebAssembly.Memory({initial:10});
    
    0 讨论(0)
  • 2021-02-19 08:52

    WebAssembly does not offer any instructions to deallocate memory, there is only the ability to increase the allocated size. Practically speaking, this means that the peak memory usage of your WebAssembly application is also the permanent memory usage.

    For a given problem, it may be possible to tweak your algorithm to reduce the peak amount of memory.

    I don't have the knowledge or ability to test this, but one out-of-the-box idea would be to try and have multiple WebAssembly runtimes distinct from each other. You could chew up a lot of memory in one to compute a relatively small result, serialize that result outside of the WASM runtime, then throw it away and spin up a new one. This is likely only to be useful in certain specific problem domains.


    In the future, memory resizing may be re-added to WebAssembly. It was explicitly removed before the MVP release:

    After the MVP, we are moving to things that diverge and cannot be polyfilled, and memory resizing makes more sense to add at that point in time.

    • Remove memory resizing from the MVP (294)
    • Only allow memory growth in MVP (389)

    Thanks to alexcrichton and steveklabnik for answering this question in the Rust Discord.

    0 讨论(0)
提交回复
热议问题