msgpack-javascript icon indicating copy to clipboard operation
msgpack-javascript copied to clipboard

Reuse Encoder/Decoder instance?

Open buu700 opened this issue 3 years ago • 6 comments

The readme says that encoding is 20% faster when reusing an Encoder instance. If that's the case, is there any reason not to just memoize them in encode (or at least reuse a default instance when no options are set)?

buu700 avatar Apr 29 '21 16:04 buu700

That's a good question. There's an example in test/reuse-instances.test.ts, but they only accepts positional parameters right now, so I might change their interfaces to accept named parameters just like as encode({...}) and decode({...}).

gfx avatar Apr 30 '21 01:04 gfx

Oh, just to clarify, I wasn't asking about the documentation. I was suggesting an optimization to the default encode and decode functions / wondering whether there was a non-obvious reason that that hadn't been done.

buu700 avatar Apr 30 '21 01:04 buu700

Ah, sorry! Misunderstood.

There're some reasons that we cannot memorize them:

  • instance.*Async() are not async-await safe (or not thread-safe)
  • the instance has lots of configuration parameters so it's difficult to memoize

gfx avatar Apr 30 '21 01:04 gfx

Got it, that makes sense. If memoizing isn't an option, what about just pre-initializing a default instance that gets used when options is undefined? That would at least cover the most common case (I'm assuming).

buu700 avatar Apr 30 '21 01:04 buu700

Sounds good. Will try it.

gfx avatar Apr 30 '21 05:04 gfx

Nice, thanks! I'd be happy to submit a PR if that would be helpful.

buu700 avatar Apr 30 '21 18:04 buu700