~/rust $ cat 0001-or-insert-vs-or-insert-with.md

HashMap entry: or_insert builds the value even when the key exists

Rust Gotcha #0001 · or_insert vs or_insert_with, same for BTreeMap

or_insert(make_value()) always runs make_value(), even when the key is already in the map. or_insert_with(|| make_value()) only runs it when the key is new.

Nothing new here: Rust evaluates a method's arguments before it calls the method, just like Java and most other languages. I know that, but it didn't occur to me at the moment I wrote the code, while aggregating weather stations for the One Billion Row Challenge. Then I saw the same thing in someone else's code, so I'm writing it down to make it stick.

What happens

In a chain like this, every method is always called. and_modify doesn't skip anything; it hands the same Entry on, and each method checks for itself whether the key exists:

location_to_measurement.entry(location.to_string())
    .and_modify(|m| m.update(measurement))
    .or_insert(MeasurementStats::new(measurement));

And because the arguments are evaluated first, MeasurementStats::new(measurement) runs on every line, and or_insert throws the result away when the station is already in the map. Only the insert itself happens just for a new station.

The fix

or_insert_with takes a closure instead of a value, a recipe for making the value, and only calls it when the key is new:

location_to_measurement.entry(location.to_string())
    .and_modify(|m| m.update(measurement))
    .or_insert_with(|| MeasurementStats::new(measurement));
Station already in the map New station
and_modify(...) called, updates the value called, does nothing
or_insert(new(...)) called, new runs and the result is thrown away called, new runs and the result is inserted
or_insert_with(|| new(...)) called, the closure is not called called, the closure runs and the result is inserted

Does it matter?

It depends on what building the value costs.

Here MeasurementStats is just four numbers, 16 bytes on the stack or in registers, with no heap allocation (new in Rust is only a function name, not Java's new). I expected or_insert to cost about four extra stores per row, so ~4 billion instructions over a billion rows. The measured difference was 0.98 billion instructions in total, less than one per row, which is within run-to-run noise.

So I looked at the generated assembly of both versions with cargo asm:

cargo asm --bin david david::main --rust > or_insert.s
# switch to or_insert_with and rebuild
cargo asm --bin david david::main --rust > or_insert_with.s
diff or_insert.s or_insert_with.s   # no output: identical

They are identical. After inlining new, the compiler sees that the value is only used when the key is missing, and builds it only in that branch. Here or_insert ended up exactly as lazy as or_insert_with.

That only works because new is cheap and has no side effects. If building the value allocates (a String, a Vec), prints something, or calls code the compiler can't see into, it runs on every call, and then or_insert_with is what makes it lazy. So I still write or_insert_with whenever the value comes from a function call: it says what I mean and doesn't depend on the optimizer.

The same pattern elsewhere

The same value / closure pairs show up all over Rust:

Eager (value) Lazy (closure)
or_insert or_insert_with
unwrap_or unwrap_or_else
ok_or ok_or_else

Clippy has a lint for the eager version, or_fun_call, which warns when a function call is passed where a closure would do. It's in the nursery group, so plain cargo clippy stays silent. You have to turn it on:

cargo clippy -- -W clippy::or_fun_call
warning: function call inside of `or_insert`
All gotchas#0002 →