Avoid doing an extra pass over strings in the cases when the min/max number of bytes for the length-prefix is not bounded. #25018
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.
Avoid doing an extra pass over strings in the cases when the min/max number of bytes for the length-prefix is not bounded.
Finding the encoded lengths of strings is slow, so to avoid doing work we usually can first see how many bytes the length-prefix-varint will need, leave that much space, encode the string to see how long it is, and then jump back to write the length in front.
But, in some cases we can't tell how many bytes the length prefix will take: for example a string that is 100 chars long will encode to 100 bytes if it was ascii but 300 bytes long if it was all emojis. The size encoded as a varint would be 1-byte in the first case and 2 bytes in teh second, so it can't know.
Instead of doing 2 pass in this situation, just Utf8 encode to a tmp byte[] first, write the length and bytes.
When this code was orginilly written, doing 2 passes was better, but in 2025 where the java.lang.Strings have alternate internal represantions that we cannot access, as well as advancements in JIT technology for the tmp allocation to typically not need GC, this is better.