Support creating a Raw buffer from a str - #252
Merged
Merged
Conversation
Previously `Raw` objects could only be created from a buffer-like
object. Since some JSON tooling in Python returns `str` rather than
`bytes` types, it makes sense to also support creating a `Raw` object
from a `str`. This saves a method call to `str.encode("utf-8")` on the
user's side.
Member
Author
|
In a quick benchmark, this measurably decrease the cost of creating a In [1]: def make_str():
...: items = "1,2,3,4,5" * 1000
...: return f"[{items}]"
...:
In [2]: from msgspec import Raw
In [3]: %timeit make_str()
538 ns ± 1.52 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
In [4]: %timeit Raw(make_str())
592 ns ± 0.427 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
In [5]: %timeit Raw(make_str().encode("utf-8"))
833 ns ± 1.02 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)One place where this comes up is defining a custom With this change, an def enc_hook(x):
if isinstance(x, pydantic.BaseModel):
return msgspec.Raw(x.json()) # previously this would be `msgspec.Raw(x.json().encode("utf-8"))`
... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Previously
Rawobjects could only be created from a buffer-like object. Since some JSON tooling in Python returnsstrrather thanbytestypes, it makes sense to also support creating aRawobject from astr. This saves a method call tostr.encode("utf-8")on the user's side.