skip to content

As the lead on a Rust game engine, what code-review rule would you set for `clone()` calls, especially inside the per-frame render loop?

level: principalimportance: should knowfreq 35%

answer

  1. not every clone costs the same
  2. hot path versus setup code
  3. borrow, reuse, or make it Copy
  4. lints for the mechanical cases

basics

~20 s

Treat clone() on heap-owning types in per-frame code as a review stop: borrow, reuse buffers with clone_from, or make small value types Copy. Outside hot paths, a clone that keeps code simple is fine. Lint the mechanical cases; profile the rest.

solid answer

~50 s

I would not ban `clone()`; I would sort clones by cost and by where they run. Small plain-data types such as `Vec2`, colours and entity ids should derive `Copy`, and `.clone()` on them is noise that Clippy's default `clone_on_copy` lint already flags. Cloning a `String`, a `Vec` or a struct that owns them allocates and copies, and in a loop that runs per sprite per frame that can add up to thousands of allocations a second, so there the rule is: borrow (`&str`, `&Sprite`), reuse a buffer with `clone_from` (which `String` documents as avoiding reallocation if possible), or justify it with a profile. Outside per-frame code (loading, config, tests, error paths) a clone that keeps ownership simple is acceptable. A clone that exists only to quiet the borrow checker gets flagged for a design look. Lints catch the mechanical cases; profiling settles the rest.

code

rust · 32 lines
rust
#[derive(Debug, Clone, Copy)]
struct Vec2 {
    x: f32,
    y: f32,
}

#[derive(Debug, Clone)]
struct Sprite {
    name: String,
    pos: Vec2,
}

fn draw(name: &str, pos: Vec2, label: &mut String) {
    label.clear();
    label.push_str(name); // reuse one buffer instead of a fresh String
    let _ = (label.len(), pos.x + pos.y);
}

fn main() {
    let sprites = vec![
        Sprite { name: "goblin".to_owned(), pos: Vec2 { x: 1.0, y: 2.0 } },
        Sprite { name: "orc".to_owned(), pos: Vec2 { x: 3.0, y: 4.0 } },
    ];
    let mut label = String::with_capacity(64);
    for frame in 0..3 {
        for s in &sprites {
            // Review flag: `let s = s.clone();` here would allocate per sprite per frame.
            draw(&s.name, s.pos, &mut label); // borrow the String, copy the Vec2
        }
        println!("frame {frame}: last label {label}");
    }
}

go deeper

for a junior

Recall that clone() on a String or Vec allocates and copies, while Copy types like a Vec2 never need a clone() call at all.

for a middle

Explain the cost classes: Copy duplicates bytes, a heap-owning clone allocates, a reference clone copies only the pointer, and a counted handle bumps a count.

for a senior

Show you would spot per-frame clones in review, replace them with borrows or clone_from, and confirm the gain with a profiler instead of guessing.

for a principal

Own the trade-off: strict, lint-backed rules in hot paths for a stable frame time, relaxed rules elsewhere for readability, and Copy decisions treated as API commitments.

## Why a blanket rule fails Two blanket rules are popular and both are wrong for a game engine: - **"Never clone."** This pushes engineers into lifetime gymnastics and borrowed fields in long-lived structs to save one allocation at startup. It costs readability where performance does not matter. - **"Clone whenever the compiler complains."** This hides allocations in code that runs sixty or more times a second, once per entity, and turns ownership questions into a slow frame budget. A good rule is about **cost class** and **location**, because `clone()` means different things on different types. The standard library's own documentation says what "duplicate" means "varies by type": a deep, independent copy for most types, another reference for `&T`, and a count increment for reference-counted pointers. The method is also marked `#[must_use = "cloning is often expensive and is not expected to have side effects"]`. ## Cost classes a reviewer should recognise | What is cloned | What `clone()` does | Review stance | |---|---|---| | `Copy` type (`Vec2`, `Rgba`, ids) | copies the value's bytes | should not appear; use the value | | `String`, `Vec<T>`, owning structs | allocates and copies the data | justify in hot paths | | `&T` where `T` is not `Clone` | copies the reference | a bug signal (`noop_method_call`) | | reference-counted handle | bumps a counter | a separate discussion, covered with smart pointers | ## The rule I would write 1. **Make small plain-data types `Copy`.** The standard library advises implementing `Copy` whenever a type can, so derive `Clone, Copy` on positions, sizes, colours and handles that own nothing, and never call `.clone()` on them in concrete code. 2. **No clones of heap-owning values in per-frame code without a reason in the review.** Pass `&str` and `&Sprite`; copy only the `Copy` fields you need. 3. **Reuse buffers.** When a per-frame string or vector must be refilled, keep one and use `clear` plus `push_str`, or `clone_from`, which `String` and `Vec` document as avoiding reallocation "if possible". 4. **Allow clones that buy clarity outside hot code**: asset loading, config parsing, tests, error reporting, one-off tools. 5. **Flag a clone added only to satisfy the borrow checker.** It may be fine, or the data layout may need restructuring; that judgment belongs with borrow-checker design, but the review should raise it. 6. **Back performance claims with a profile**, not with a count of `.clone()` calls. ## Tooling that enforces the mechanical part - Clippy's **`clone_on_copy`** lint is on by default and flags `.clone()` on a `Copy` type. - Clippy's **`redundant_clone`** lint finds a clone of an owned value that is dropped without further use. In Clippy 1.99 it sits in the `nursery` group, so a team must opt in, and its own documentation warns that the analysis is "conservative and limited", so false negatives are expected. - rustc's **`noop_method_call`** lint, on by default, warns when `.clone()` on a `&T` only copies the reference. Lint configuration across a workspace belongs to the Cargo lints setup; the review rule only decides which ones the team turns on. ## Where the rule bends - **Large `Copy` types** are copied silently on every by-value pass, so a struct wrapping a `[f32; 4096]` that derives `Copy` can cost more per frame than a visible `clone()`; keep `Copy` for small types. - **`Copy` is a public API promise.** The standard library warns that implementing it "is part of the public API of your type"; removing it later breaks callers, so a type that may grow a `String` field should stay `Clone`-only. - **A derived `Clone` is not always deep.** A field that is a shared, reference-counted pointer to a lock makes the clone share mutable state with the original; the standard library calls this out explicitly. ## Signals in review - `let s = s.clone();` at the top of a loop body that only reads `s`. - `.clone()` passed straight into a function that takes `&T`. - `.to_string()` or `format!` building the same label every frame. - A struct that clones a whole `Vec` each tick to hand it to one system. The trade-off a lead owns is explicit: a little ownership complexity in per-frame code in exchange for a stable frame time, and simple owned values everywhere else.

  • Would you make every small struct `Copy` to avoid `clone()` calls?
    Most plain-data types, yes: the standard library advises implementing `Copy` when a type can. But `Copy` is a public API promise that is breaking to remove, and large `Copy` types are copied silently on every by-value pass. I keep it for small types that will stay plain data.
  • How would you enforce the rule without blocking every pull request on style?
    Keep Clippy's default lints, including `clone_on_copy`, failing CI, and opt into `redundant_clone` knowing it is a `nursery` lint with false negatives. For per-frame modules, ask for a one-line reason or a profile on any clone of a heap-owning value; elsewhere, accept clones that simplify ownership.
  • Does a derived `Clone` always produce a deep copy?
    No. A derived `clone` calls `clone` on each field, so it is only as deep as each field's own `Clone`. A field holding a reference-counted pointer to a mutex gets a new handle to the same mutex, and the clone shares mutable state with the original, as the standard library documentation warns.

  • Every clone() is a performance bug and should be banned
  • The optimiser always removes clones, so they cost nothing
  • Making a type Copy is free and can be undone at any time
  • Clippy's redundant_clone lint catches every unnecessary clone
  • A derived Clone always gives a fully independent deep copy

Assumes Rust 1.99.1 and its bundled Clippy, where clone_on_copy is on by default and redundant_clone sits in the opt-in nursery group; lint groups can change between releases.