8.6 The Cost of Clone and When to Avoid It
Alright, let’s talk about Clone. It’s the “I need one of those too” trait. You see an object, you want an exact replica, you call .clone(). Simple, right? The problem is, it’s a siren song. It’s so easy to use that it becomes the go-to solution for any ownership problem, and that’s how you end up with a codebase that’s slower than a snail on sedatives. The fundamental thing you must internalize is this: Clone is explicit, but not necessarily cheap. Unlike the Copy trait, which is a blind, cheap bit-for-bit duplication happening implicitly behind the scenes, Clone is an explicit method call. You are asking for a duplication. And what happens inside that method is entirely up to the type’s implementation. For a String or a Vec, it means allocating a whole new chunk of memory and copying every single byte over. That’s an O(n) operation. Do that in a tight loop and you’ve just built a performance bottleneck.