Daninet / gmp-wasm

Arbitrary-precision Integer, Rational and Float types based on the GMP and MPFR libraries
GNU Lesser General Public License v3.0
21 stars 4 forks source link

Memory management #5

Open danwallach opened 2 years ago

danwallach commented 2 years ago

I'm looking at the way you're managing memory, by keeping mpz_t_arr for all the temporary values and then blowing all of them away when the surrounding context finishes. I'm curious if you've looked at the possibility of leveraging finalizers, to allow the JavaScript garbage collector call back to you when it's time to ultimately call mpz_t_free.

This would allow higher-level logic to write arithmetic expressions as normal, without having to worry about object lifetimes.

Daninet commented 2 years ago

Yeah, this would be interesting to explore. I planned to evaluate it together with the WebAssembly GC proposal when it appears in the engines.

In my use case, I only use reset(), which recreates the whole WASM memory region and it's super fast. I'm afraid that finalizers might create memory fragmentation which would randomly slow down the allocation of new objects.

Also writing a custom memory allocator in C is something that might be interesting to play with.

Daninet commented 2 years ago

I have one more idea to explore:

danwallach commented 2 years ago

I'm currently playing with building a finalizer-based wrapper that internally calls mpz_t_free. If I can somehow get it to work, I'll let you know.

jacobp100 commented 1 year ago

I had a poke over here - https://github.com/jacobp100/mpfr

It does work. My end goal is to have it work with React Native, which doesn't have a finalization registry or wasm. You can provide an exports-like object that calls native functions, but for GC you register your own types with destructors (which is why there's a reference to gcHandle)