I figured if we encode into a temporary array first and then call a single write_str the performance improves quite a lot.
With reasonably simple unsafe we can squeeze out a bit better performance on top of that.
Relevant benchmarks - encoding 32B:
test tests::thirtytwo::trivial::sink ... bench: 1,577 ns/iter (+/- 567)
test tests::thirtytwo::trivial::string ... bench: 1,882 ns/iter (+/- 194)
test tests::thirtytwo::with_buf::sink ... bench: 57 ns/iter (+/- 29)
test tests::thirtytwo::with_buf::string ... bench: 92 ns/iter (+/- 3)
test tests::thirtytwo::with_unsafe::sink ... bench: 47 ns/iter (+/- 21)
test tests::thirtytwo::with_unsafe::string ... bench: 92 ns/iter (+/- 12)
test tests::thirtytwo::maybe_uninit::sink ... bench: 43 ns/iter (+/- 6)
test tests::thirtytwo::maybe_uninit::string ... bench: 79 ns/iter (+/- 40)
trivial is the current impl, with_buf uses temporary buffer without unsafe, with_unsafe uses unsafe only to call from_utf8_unchecked, maybe_uninit also uses uninit buffer. (IOW "more unsafe")
sink only passes the buffer into black box, while string calls to_string(). The performance difference is larger here because a single write avoids reallocation.
Full bench code with other benchmarks
I intend to submit a PR with this together with other refactors mentioned earlier, my question is if I should use unsafe or not.
I figured if we encode into a temporary array first and then call a single
write_strthe performance improves quite a lot.With reasonably simple
unsafewe can squeeze out a bit better performance on top of that.Relevant benchmarks - encoding 32B:
trivialis the current impl,with_bufuses temporary buffer withoutunsafe,with_unsafeusesunsafeonly to callfrom_utf8_unchecked,maybe_uninitalso uses uninit buffer. (IOW "moreunsafe")sinkonly passes the buffer into black box, whilestringcallsto_string(). The performance difference is larger here because a single write avoids reallocation.Full bench code with other benchmarks
I intend to submit a PR with this together with other refactors mentioned earlier, my question is if I should use
unsafeor not.