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

Rust: Don't unnecessarily create new Vecs for every request. #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

dcormier
Copy link

@dcormier dcormier commented Oct 23, 2022

Using .unwrap_or(&Vec::new()) will allocate create a new Vec every time the code is executed, whether or not the value being unwrapped is None.

Using .unwrap_or_default() will only allocate create a new Vec if the value being unwrapped is None.

@CosmicHorrorDev
Copy link

Vec::new() actually does not allocate. I would be surprised if this caused a perf diff. Quoting the docs

The vector will not allocate until elements are pushed onto it.

@dcormier
Copy link
Author

A new Vec struct is allocated and returned by Vec::new() (source). It's internal storage is empty, though.

I have not run a benchmark comparison.

@CosmicHorrorDev
Copy link

I think we're using terminology differently. I'm used to allocate meaning specifically heap allocations, not just creating some struct in general

@dcormier dcormier changed the title Rust: Don't unnecessarily allocate new Vecs for every request. Rust: Don't unnecessarily create new Vecs for every request. Oct 23, 2022
Using `.unwrap_or(&Vec::new())` will create a new `Vec` [every time the code is executed](https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or), whether or not the value being unwrapped is `None`.

Using `.unwrap_or_default()` will only create a new `Vec` if the value being unwrapped is `None`.
@coder543
Copy link

I have to agree that calling Vec::new() shouldn't really affect performance since it doesn't cause heap allocations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants