Optimize binary encode/decode in Tuple layer #57
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
I found performance problems with
erlfdb_tuple:enc_null_terminated/1anderlfdb_tuple:dec_null_terminated/1.The problem is that the current implementation goes searching for
?NULLs and?ESCAPEs with iterative Erlang function calls. The overhead becomes very noticeable as the strings grow in size, or if the frequency of0bytes increases.Solution
Avoid iterating on each byte in Erlang code. Instead, use the optimized
binary:match/3.Aside -- why can't we do even better?
In many existing binary protocols, a string would be encoded with its length prefixed and without escaping. However, in the Tuple layer, this is not possible because the encoding must provide the correct ordering for variable length strings. Prefixing the string length would break this contract. We will always have to do iterative searching for the
?NULLand?ESCAPE. It turns out the OTP team has already optimized this for us inbinary:match/3.Benchmark
For each run:
0byte within.0bytes.Result
Summary
For a 32-byte string without an escaped 0 byte, the execution is reduced by 50%.
For such a 512-byte string, by 98%.
Details
Results from current erlfdb master
Results with the proposed changes
Benchmark Code