Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make json macro pre-allocate capacity for maps #810

Open
dtolnay opened this issue Oct 9, 2021 · 0 comments · May be fixed by #876
Open

Make json macro pre-allocate capacity for maps #810

dtolnay opened this issue Oct 9, 2021 · 0 comments · May be fixed by #876

Comments

@dtolnay
Copy link
Member

dtolnay commented Oct 9, 2021

Currently an invocation like json!({ "x": 0, "y": 'y' as i8, "z": [] }) expands into:

::serde_json::Value::Object({
    let mut object = ::serde_json::Map::new();
    let _ = object.insert(...);
    let _ = object.insert(...);
    let _ = object.insert(...);
    object
})

It would be better if it were able to allocate capacity up front, such as by:

-   let mut object = ::serde_json::Map::new();
+   let mut object = ::serde_json::Map::with_capacity(1 + 1 + 1);
zachs18 added a commit to zachs18/json that referenced this issue Apr 5, 2022
Attempt to address issue serde-rs#810.

This implementation works by expanding the contents of the map twice,
first to increment a capacity variable for each element, then actually
inserting them.

In debug mode, this implementation does not appear to optimize out the incrementations
of the capacity variable, so it is likely not a good solution.
zachs18 added a commit to zachs18/json that referenced this issue Apr 5, 2022
Attempt to address issue serde-rs#810.

This implementation works by expanding the contents of the map twice,
first to produce a capacity value, then actually inserting the elements.

Because it expands the contents of the map twice, when encountering invalid syntax,
it may print error messages twice, which may be unwanted.
@zachs18 zachs18 linked a pull request Apr 5, 2022 that will close this issue
zachs18 added a commit to zachs18/json that referenced this issue Oct 26, 2022
Attempt to address issue serde-rs#810.

This implementation works by expanding the contents of the map twice,
first to produce a capacity value, then actually inserting the elements.

Because it expands the contents of the map twice, when encountering invalid syntax,
it may print error messages twice, which may be unwanted.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging a pull request may close this issue.

1 participant