Course contentsShow
← Rust
Lesson 347 of 1,9104. Lifetimes and Advanced OwnershipFree lesson

The Cost of Cloning

Identify performance bottlenecks caused by excessive heap allocation during duplication.

In this lesson, you will learn how to identify hidden performance bottlenecks caused by excessive heap allocations when using the .clone() method.

The Hidden Price of .clone()

When we talk about ownership in Rust, we often emphasize that "moving" a value is cheap—it just copies a few bytes on the stack. However, when you call .clone() on types like String, Vec<T>, or HashMap, Rust does not just copy the metadata on the stack. Instead, it performs a deep copy.

A deep copy requires allocating new memory on the heap, copying every element from the original data structure to the new location, and updating the pointers. This is an O(n)O(n) operation, meaning the time it takes grows linearly with the size of your data. If you are doing this inside a tight loop, your program’s performance will degrade significantly because you are repeatedly asking the system for more memory and filling it up.

Identifying the Bottleneck

Consider this scenario:

fn process_data(data: Vec<String>) {
    for item in data {
        // Cloning inside a loop is a major performance red flag!
        let worker_copy = item.clone(); 
        perform_task(worker_copy);
    }
}

In the code above, if item is a large string, item.clone() forces the allocator to find a new block of heap memory for every single iteration. If you have 10,000 items, you perform 10,000 heap allocations.

To optimize this, ask yourself: "Do I truly need an independent copy of this data?" Often, you don't. By passing a reference (&String) instead of a clone, you allow the function to look at the data without duplicating it. If you need ownership, consider if you can "move" the value instead of cloning it, which transfers the existing heap pointer rather than creating a new one.

Whenever you see the .clone() method in your code, treat it as a warning sign. It is a signal that you are about to pay the price of a heap allocation. Always look for ways to borrow the data first.

Key Takeaway: Use .clone() only as a last resort, as it triggers expensive heap allocations that can drastically slow down your program.