En bref. Quand une valeur est utilisée après avoir été déplacée, rustc propose de la cloner, « si le coût est acceptable ». Ce coût est concret : cloner une String alloue un tampon et copie le texte. Souvent, la fonction n’avait besoin que de lire, et un emprunt suffisait. Et quand une fonction modifie parfois son entrée, Cow permet de ne payer l’allocation que ces fois-là.
Le modèle en une phrase
Une
Stringpossède un tampon dans le tas. La déplacer change le propriétaire du tampon, la cloner en alloue un second, l’emprunter n’en crée aucun.Cowest un emprunt qui ne devient une copie que lorsqu’il faut écrire.
L’animation compte les tampons : d’abord pour un déplacement, un clone et un emprunt, puis pour une fonction qui rend un Cow.
In short. When a value is used after being moved, rustc suggests cloning it, “if the performance cost is acceptable”. That cost is concrete: cloning a String allocates a buffer and copies the text. Often the function only needed to read, and a borrow was enough. And when a function sometimes modifies its input, Cow lets you pay the allocation only those times.
The model in one sentence
A
Stringowns a buffer on the heap. Moving it changes the owner of the buffer, cloning it allocates a second one, borrowing it creates none.Cowis a borrow that only becomes a copy when something has to be written.
The animation counts the buffers: first for a move, a clone and a borrow, then for a function that returns a Cow.
let nom = String::from("Ada");
nomest uneString. Sur la pile, elle tient en trois champs : un pointeur, une longueur, une capacité. Le texte lui-même est dans un tampon du tas, quenompossède. Créer cetteStringa coûté une allocation.nomis aString. On the stack, it is three fields: a pointer, a length, a capacity. The text itself lives in a heap buffer, whichnomowns. Creating thisStringcost one allocation.longueurprend uneStringpar valeur : l'appel déplacenomdans le paramètres. Aucune copie, le tampon change seulement de propriétaire. Maisnomn'est plus utilisable, et la ligne suivante est refusée : E0382. L'aide du compilateur proposenom.clone(), if the performance cost is acceptable.longueurtakes aStringby value: the call movesnominto the parameters. No copy, the buffer only changes owner. Butnomcan no longer be used, and the next line is rejected: E0382. The compiler's help suggestsnom.clone(), if the performance cost is acceptable.- Avec
nom.clone(), le programme compile. Le clone alloue un second tampon et y copie les octets ; c'est cette copie quelongueurreçoit, lit, puis détruit. Le compteur passe à deux allocations, alors que la fonction n'avait besoin que de lire.Withnom.clone(), the program compiles. The clone allocates a second buffer and copies the bytes into it; that copy is whatlongueurreceives, reads, then destroys. The counter goes to two allocations, even though the function only needed to read. - L'autre correction change la fonction :
longueur_refprend un&str.sest alors un emprunt, un pointeur et une longueur qui désignent le tampon denom. Rien n'est alloué, rien n'est copié, etnomreste utilisable. Le compteur reste à un.The other fix changes the function:longueur_reftakes a&str.sis then a borrow, a pointer and a length that designate the buffer ofnom. Nothing is allocated, nothing is copied, andnomstays usable. The counter stays at one.
Ce que le compilateur propose
Le point de départ est une erreur que tout le monde rencontre. Une fonction prend une String, et l’appelant veut encore s’en servir ensuite :
fn afficher(s: String) {
println!("bonjour {s}");
}
fn main() {
let nom = String::from("Ada");
afficher(nom);
println!("{nom}");
}error[E0382]: borrow of moved value: `nom`
--> deplace.rs:8:16
|
6 | let nom = String::from("Ada");
| --- move occurs because `nom` has type `String`, which does not implement the `Copy` trait
7 | afficher(nom);
| --- value moved here
8 | println!("{nom}");
| ^^^ value borrowed here after move
|
note: consider changing this parameter type in function `afficher` to borrow instead if owning the value isn't necessary
--> deplace.rs:1:16
|
1 | fn afficher(s: String) {
| -------- ^^^^^^ this parameter takes ownership of the value
| |
| in this function
help: consider cloning the value if the performance cost is acceptable
|
7 | afficher(nom.clone());
| ++++++++Le message contient deux corrections, et elles ne se valent pas.
- La note, en premier : changer le paramètre pour qu’il emprunte, if owning the value isn’t necessary. Elle demande de modifier la fonction.
- L’aide, en dernier : ajouter
.clone(), if the performance cost is acceptable. Elle tient en huit caractères, au point d’appel, avec le correctif prêt à copier.
La seconde est la plus facile à appliquer, donc la plus appliquée. Le reste de l’article mesure ce qu’elle coûte.
Ce que coûte un clone
Pour le voir, on remplace l’allocateur global par un allocateur qui compte ses appels, puis on mesure les deux écritures :
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Compteur;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Compteur {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
unsafe { System.dealloc(p, l) }
}
}
#[global_allocator]
static A: Compteur = Compteur;
fn allocs() -> usize {
ALLOCS.load(Ordering::Relaxed)
}
fn par_valeur(s: String) -> usize {
s.len()
}
fn par_emprunt(s: &str) -> usize {
s.len()
}
fn main() {
let nom = String::from("Ada Lovelace");
let avant = allocs();
let n = par_valeur(nom.clone());
let clone = allocs() - avant;
let avant = allocs();
let m = par_emprunt(&nom);
let emprunt = allocs() - avant;
let copie = nom.clone();
let meme = nom.as_ptr() == copie.as_ptr();
println!("clone : {clone} allocation");
println!("emprunt : {emprunt} allocation");
println!("longueurs : {n} et {m}");
println!("même tampon : {meme}");
}clone : 1 allocation
emprunt : 0 allocation
longueurs : 12 et 12
même tampon : falseLes deux fonctions rendent le même résultat. La première a demandé de la mémoire au système, copié douze octets, puis libéré cette mémoire à la fin de l’appel. La seconde a reçu un pointeur et une longueur.
La dernière ligne montre ce qu’est un clone : nom et copie ont le même contenu, mais pas le même tampon.
pile tas
nom ┌ ptr ──────────────────▶ ┌──────────────┐
│ len 12 │ Ada Lovelace │
└ cap 12 └──────────────┘
copie ┌ ptr ──────────────────▶ ┌──────────────┐ nom.clone() :
│ len 12 │ Ada Lovelace │ une allocation,
└ cap 12 └──────────────┘ douze octets copiés
s ┌ ptr ──────────▶ (le tampon de nom) &nom :
└ len 12 rien d'allouéCopy et Clone : où passe la frontière
Certains types se copient sans qu’on l’écrive, d’autres non. La règle tient à ce que la valeur possède.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let n = 5;
let m = n;
println!("{n} {m}");
let p = Point { x: 1, y: 2 };
let q = p;
println!("{p:?} {q:?}");
let s = String::from("Ada");
println!("String : {} octets sur la pile, {} dans le tas", std::mem::size_of_val(&s), s.len());
}5 5
Point { x: 1, y: 2 } Point { x: 1, y: 2 }
String : 24 octets sur la pile, 3 dans le tasUn i32 ou un Point tient tout entier sur la pile. Le copier, c’est dupliquer quelques octets : le langage le fait implicitement, et les deux variables restent utilisables. Ces types sont Copy.
Une String fait 24 octets sur la pile, mais ces octets ne sont que la poignée d’un tampon. Les dupliquer donnerait deux propriétaires au même tampon, donc deux libérations. Le langage refuse cette copie implicite : il déplace. Et il refuse aussi qu’on la force :
#[derive(Clone, Copy)]
struct Client {
nom: String,
}error[E0204]: the trait `Copy` cannot be implemented for this type
--> copystr.rs:2:8
|
1 | #[derive(Clone, Copy)]
| ---- in this derive macro expansion
2 | struct Client {
| ^^^^^^
3 | nom: String,
| ----------- this field does not implement `Copy`
Copy | Clone | |
|---|---|---|
| Écriture | aucune : let m = n; | explicite : x.clone() |
| Ce qui est copié | les octets de la valeur, sur la pile | ce que le type décide, tas compris |
| Coût | fixe et petit | dépend du type et de la taille |
| Exemples | i32, bool, char, &T | String, Vec<T>, HashMap<K, V> |
Clone existe donc pour que la copie coûteuse soit visible dans le code. Un .clone() est un endroit où le programme peut allouer.
Un clone peut en cacher mille
Le coût d’un clone dépend de ce que la valeur contient. Avec le même compteur d’allocations :
fn main() {
let noms: Vec<String> = (0..1000).map(|i| format!("utilisateur numéro {i}")).collect();
let avant = allocs();
let copie = noms.clone();
let n_vec = allocs() - avant;
let partage = Arc::new(noms);
let avant = allocs();
let autre = Arc::clone(&partage);
let n_arc = allocs() - avant;
let avant = allocs();
let profond = (*partage).clone();
let n_profond = allocs() - avant;
println!("Vec<String>::clone : {n_vec} allocations");
println!("Arc::clone : {n_arc} allocation");
println!("(*partage).clone() : {n_profond} allocations");
println!("propriétaires de l'Arc : {}", Arc::strong_count(&partage));
let _ = (copie.len(), autre.len(), profond.len());
}Vec<String>::clone : 1001 allocations
Arc::clone : 0 allocation
(*partage).clone() : 1001 allocations
propriétaires de l'Arc : 2Trois écritures qui se ressemblent, trois coûts.
- Cloner le
Vecclone chaque élément : une allocation pour le tableau, plus une parString. Soit 1001 pour mille noms. - Cloner l’
Arcn’alloue rien : il incrémente un compteur et rend un second pointeur vers les mêmes données. C’est pour ça que la convention est d’écrireArc::clone(&partage)plutôt quepartage.clone(): on voit à la lecture que ce clone-là est bon marché. (*partage).clone()déréférence l’Arcet clone son contenu : retour à 1001. La différence avec la ligne précédente tient à une étoile.
Emprunter au lieu de cloner
Dans le premier exemple, afficher ne fait que lire son argument. La correction que la note du compilateur suggère est de le dire dans la signature :
fn afficher(s: &str) {
println!("bonjour {s}");
}
fn main() {
let nom = String::from("Ada");
afficher(&nom);
println!("{nom}");
}Le choix du type de paramètre suit ce que la fonction fait de la valeur :
| La fonction… | Paramètre | L’appelant écrit | Allocation |
|---|---|---|---|
| lit un texte | &str | f(&nom) | aucune |
| lit une liste | &[T] | f(&v) | aucune |
| lit une struct | &T | f(&config) | aucune |
| modifie sur place | &mut T | f(&mut v) | aucune |
| garde la valeur (la range, l’envoie à un thread) | T | f(nom) ou f(nom.clone()) | seulement si l’appelant clone |
La dernière ligne compte : quand la fonction a vraiment besoin de posséder, prendre T par valeur est le bon choix. L’appelant décide alors lui-même s’il donne sa valeur ou s’il en garde une copie.
Cow : ne copier que s’il le faut
Reste un cas que ni &str ni String ne couvrent bien : une fonction qui rend le plus souvent son entrée telle quelle, et parfois une version modifiée. Par exemple, remplacer les espaces par des tirets bas :
fn toujours(s: &str) -> String {
s.replace(' ', "_")
}Cette version alloue à chaque appel, même quand l’entrée ne contient aucun espace. Cow (clone on write) permet de rendre l’un ou l’autre :
use std::borrow::Cow;
fn si_besoin(s: &str) -> Cow<'_, str> {
if s.contains(' ') {
Cow::Owned(s.replace(' ', "_"))
} else {
Cow::Borrowed(s)
}
}
fn variante(c: &Cow<'_, str>) -> &'static str {
match c {
Cow::Borrowed(_) => "Borrowed",
Cow::Owned(_) => "Owned",
}
}
fn main() {
let lot = ["ada", "grace hopper", "linus"];
let avant = allocs();
for s in lot {
let _propre = toujours(s);
}
let n_string = allocs() - avant;
let mut n_cow = 0;
for s in lot {
let avant = allocs();
let propre = si_besoin(s);
let n = allocs() - avant;
n_cow += n;
println!("{propre:<12} {:<8} {n}", variante(&propre));
}
println!("String : {n_string} allocations");
println!("Cow : {n_cow} allocation");
}ada Borrowed 0
grace_hopper Owned 1
linus Borrowed 0
String : 3 allocations
Cow : 1 allocationCow n’a rien de magique : c’est un enum à deux variantes.
Cow<'a, str>
├─ Borrowed(&'a str) un emprunt de l'entrée 0 allocation
└─ Owned(String) une nouvelle String 1 allocationL’appelant n’a pas à savoir laquelle il a reçue. Un Cow<str> se lit comme un &str : propre.len(), println!("{propre}") et toutes les méthodes de str fonctionnent sur les deux variantes.
to_mut : la copie au moment d’écrire
Un Cow emprunté peut devenir possédé plus tard. to_mut() rend un accès en écriture, et fait la copie si elle n’a pas encore eu lieu :
fn main() {
let mut c: Cow<'_, str> = Cow::Borrowed("ada");
println!("avant : {} ({c})", variante(&c));
let avant = allocs();
c.to_mut().make_ascii_uppercase();
let n = allocs() - avant;
println!("après : {} ({c})", variante(&c));
println!("to_mut : {n} allocation");
let avant = allocs();
c.to_mut().make_ascii_lowercase();
let n = allocs() - avant;
println!("encore : {} ({c}), {n} allocation", variante(&c));
}avant : Borrowed (ada)
après : Owned (ADA)
to_mut : 1 allocation
encore : Owned (ada), 0 allocationLe premier to_mut() trouve un Borrowed : il alloue, copie, et la valeur devient Owned. Le second trouve déjà un Owned et n’alloue rien. La copie a lieu une seule fois, à la première écriture.
Conséquence à connaître : appeler to_mut() sans vérifier s’il y a quelque chose à modifier annule tout le bénéfice, puisque chaque valeur empruntée est alors copiée. Le test doit venir avant.
clone sur une référence
Dernier piège : un .clone() qui ne clone pas ce qu’on croit.
struct Config {
nom: String,
}
fn main() {
let c = Config { nom: String::from("prod") };
let r = &c;
let d = r.clone();
println!("{}", d.nom);
}warning: call to `.clone()` on a reference in this situation does nothing
--> noop.rs:8:14
|
8 | let d = r.clone();
| ^^^^^^^^
|
= note: the type `Config` does not implement `Clone`, so calling `clone` on `&Config` copies the reference, which does not do anything and can be removed
= note: `#[warn(noop_method_call)]` on by defaultConfig n’est pas Clone. Mais les références partagées sont Copy, donc Clone : l’appel compile en clonant la référence. d est un second &Config, pas un Config. Le programme affiche bien prod, et aucune copie de la configuration n’existe.
Si le résultat doit être une valeur possédée, la même cause devient une erreur :
fn dupliquer(c: &Config) -> Config {
c.clone()
}error[E0308]: mismatched types
--> reft.rs:6:5
|
5 | fn dupliquer(c: &Config) -> Config {
| ------ expected `Config` because of return type
6 | c.clone()
| ^^^^^^^^^ expected `Config`, found `&Config`
|
note: `Config` does not implement `Clone`, so `&Config` was cloned instead
--> reft.rs:6:5
|
6 | c.clone()
| ^
help: consider annotating `Config` with `#[derive(Clone)]`
|
1 + #[derive(Clone)]
2 | struct Config {
|Dans les deux cas, la correction est #[derive(Clone)] sur le type. Dans du code générique, la forme est la même : une fonction qui clone un &T doit demander T: Clone.
Ce que l’image cache
- Cloner est parfois le bon geste. Quand la valeur doit vraiment exister deux fois (une copie pour un autre thread, une valeur rangée dans une struct qui vit plus longtemps), le clone est la réponse correcte. Sur une petite valeur, dans du code exécuté une fois au démarrage, son coût ne se mesure pas. Le problème est le clone écrit par réflexe sur un chemin exécuté des millions de fois.
to_owned(),to_string()etString::fromsont de la même famille. Appliqués à un&str, tous allouent uneString. Ils ne s’appellent pasclone, mais ils se comptent pareil.Cowa un prix. Chaque accès teste la variante, la signature porte un lifetime, et le type se propage chez les appelants. Si la fonction modifie toujours son entrée, rendez uneString; si elle ne la modifie jamais, rendez un&str.Cown’est justifié que pour le cas mixte, sur un chemin où l’allocation compte.Cowne se limite pas aux chaînes.Cow<[T]>fait la même chose entre&[T]etVec<T>, et plus généralementCow<B>entre&Bet sa version possédée.Rcse comporte commeArc.Rc::cloneincrémente un compteur sans rien copier.Rc::make_mutetArc::make_mutappliquent la même idée queto_mut: ils ne clonent le contenu que s’il est partagé.- Une allocation n’est pas qu’une copie. Elle passe par l’allocateur, qui doit trouver un bloc libre et plus tard le reprendre. Sur un chemin chaud, c’est souvent ce travail, plus que la copie des octets, qui coûte.
- Mesurer avant de corriger. Le compteur d’allocations de cet article tient en vingt lignes et dit où le programme alloue. C’est plus fiable que de relire le code à la recherche de
.clone().
Pour aller plus loin
- Volume 9, numéro 02 de The Rust Loop, clone, Cow & l’allocation cachée, qui part du clone écrit pour faire taire le compilateur et va jusqu’au choix entre
String,&stretCow(lien en bas de page). - Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369), dyn et vtable (E0038), règle de l’orphelin (E0117), Box et types récursifs (E0072), Rc et Arc (E0277), Cell et RefCell, threads et move (E0373), Send, Sync etArc<Mutex<T>>(E0277), les canaux mpsc (E0382), Future et .await (E0728), les fonctions colorées et Send, annuler et sélectionner, les itérateurs. - La documentation de
Cow, avecto_mutetinto_owned - Le trait
Cloneet le traitCopy, qui précise quels types peuvent êtreCopy - Le Rust Book, chapitre 4.1 : la possession, pour la pile, le tas et le déplacement
- La documentation d’
Arc, qui explique la conventionArc::clone(&x)
What the compiler suggests
The starting point is an error everyone runs into. A function takes a String, and the caller still wants to use it afterwards:
fn afficher(s: String) {
println!("bonjour {s}");
}
fn main() {
let nom = String::from("Ada");
afficher(nom);
println!("{nom}");
}error[E0382]: borrow of moved value: `nom`
--> deplace.rs:8:16
|
6 | let nom = String::from("Ada");
| --- move occurs because `nom` has type `String`, which does not implement the `Copy` trait
7 | afficher(nom);
| --- value moved here
8 | println!("{nom}");
| ^^^ value borrowed here after move
|
note: consider changing this parameter type in function `afficher` to borrow instead if owning the value isn't necessary
--> deplace.rs:1:16
|
1 | fn afficher(s: String) {
| -------- ^^^^^^ this parameter takes ownership of the value
| |
| in this function
help: consider cloning the value if the performance cost is acceptable
|
7 | afficher(nom.clone());
| ++++++++The message contains two fixes, and they are not equivalent.
- The note, first: change the parameter so that it borrows, if owning the value isn’t necessary. It asks you to modify the function.
- The help, last: add
.clone(), if the performance cost is acceptable. It is eight characters, at the call site, with the patch ready to copy.
The second is the easiest to apply, so it is the one most applied. The rest of this article measures what it costs.
What a clone costs
To see it, we replace the global allocator with one that counts its calls, then measure both spellings:
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Compteur;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Compteur {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
unsafe { System.dealloc(p, l) }
}
}
#[global_allocator]
static A: Compteur = Compteur;
fn allocs() -> usize {
ALLOCS.load(Ordering::Relaxed)
}
fn par_valeur(s: String) -> usize {
s.len()
}
fn par_emprunt(s: &str) -> usize {
s.len()
}
fn main() {
let nom = String::from("Ada Lovelace");
let avant = allocs();
let n = par_valeur(nom.clone());
let clone = allocs() - avant;
let avant = allocs();
let m = par_emprunt(&nom);
let emprunt = allocs() - avant;
let copie = nom.clone();
let meme = nom.as_ptr() == copie.as_ptr();
println!("clone : {clone} allocation");
println!("emprunt : {emprunt} allocation");
println!("longueurs : {n} et {m}");
println!("même tampon : {meme}");
}clone : 1 allocation
emprunt : 0 allocation
longueurs : 12 et 12
même tampon : false(emprunt is the borrow, longueurs the lengths, même tampon “same buffer”.) Both functions return the same result. The first asked the system for memory, copied twelve bytes, then freed that memory when the call ended. The second received a pointer and a length.
The last line shows what a clone is: nom and copie have the same content, but not the same buffer.
stack heap
nom ┌ ptr ──────────────────▶ ┌──────────────┐
│ len 12 │ Ada Lovelace │
└ cap 12 └──────────────┘
copie ┌ ptr ──────────────────▶ ┌──────────────┐ nom.clone():
│ len 12 │ Ada Lovelace │ one allocation,
└ cap 12 └──────────────┘ twelve bytes copied
s ┌ ptr ──────────▶ (the buffer of nom) &nom:
└ len 12 nothing allocatedCopy and Clone: where the line is
Some types are copied without you writing anything, others are not. The rule depends on what the value owns.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let n = 5;
let m = n;
println!("{n} {m}");
let p = Point { x: 1, y: 2 };
let q = p;
println!("{p:?} {q:?}");
let s = String::from("Ada");
println!("String : {} octets sur la pile, {} dans le tas", std::mem::size_of_val(&s), s.len());
}5 5
Point { x: 1, y: 2 } Point { x: 1, y: 2 }
String : 24 octets sur la pile, 3 dans le tasAn i32 or a Point lives entirely on the stack. Copying it means duplicating a few bytes: the language does it implicitly, and both variables stay usable. These types are Copy.
A String is 24 bytes on the stack (“sur la pile”) and 3 on the heap (“dans le tas”), but those 24 bytes are only the handle of a buffer. Duplicating them would give the same buffer two owners, hence two frees. The language refuses that implicit copy: it moves. And it also refuses to let you force it:
#[derive(Clone, Copy)]
struct Client {
nom: String,
}error[E0204]: the trait `Copy` cannot be implemented for this type
--> copystr.rs:2:8
|
1 | #[derive(Clone, Copy)]
| ---- in this derive macro expansion
2 | struct Client {
| ^^^^^^
3 | nom: String,
| ----------- this field does not implement `Copy`
Copy | Clone | |
|---|---|---|
| Spelling | none: let m = n; | explicit: x.clone() |
| What is copied | the bytes of the value, on the stack | whatever the type decides, heap included |
| Cost | fixed and small | depends on the type and the size |
| Examples | i32, bool, char, &T | String, Vec<T>, HashMap<K, V> |
So Clone exists to make the expensive copy visible in the code. A .clone() is a place where the program may allocate.
One clone can hide a thousand
The cost of a clone depends on what the value contains. With the same allocation counter:
fn main() {
let noms: Vec<String> = (0..1000).map(|i| format!("utilisateur numéro {i}")).collect();
let avant = allocs();
let copie = noms.clone();
let n_vec = allocs() - avant;
let partage = Arc::new(noms);
let avant = allocs();
let autre = Arc::clone(&partage);
let n_arc = allocs() - avant;
let avant = allocs();
let profond = (*partage).clone();
let n_profond = allocs() - avant;
println!("Vec<String>::clone : {n_vec} allocations");
println!("Arc::clone : {n_arc} allocation");
println!("(*partage).clone() : {n_profond} allocations");
println!("propriétaires de l'Arc : {}", Arc::strong_count(&partage));
let _ = (copie.len(), autre.len(), profond.len());
}Vec<String>::clone : 1001 allocations
Arc::clone : 0 allocation
(*partage).clone() : 1001 allocations
propriétaires de l'Arc : 2Three spellings that look alike, three costs.
- Cloning the
Vecclones each element: one allocation for the array, plus one perString. That is 1001 for a thousand names. - Cloning the
Arcallocates nothing: it increments a counter and returns a second pointer to the same data (the last line counts two owners). That is why the convention is to writeArc::clone(&partage)rather thanpartage.clone(): you can see when reading that this clone is cheap. (*partage).clone()dereferences theArcand clones its content: back to 1001. The difference from the previous line is one asterisk.
Borrow instead of cloning
In the first example, afficher only reads its argument. The fix suggested by the compiler’s note is to say so in the signature:
fn afficher(s: &str) {
println!("bonjour {s}");
}
fn main() {
let nom = String::from("Ada");
afficher(&nom);
println!("{nom}");
}The choice of parameter type follows what the function does with the value:
| The function… | Parameter | The caller writes | Allocation |
|---|---|---|---|
| reads a text | &str | f(&nom) | none |
| reads a list | &[T] | f(&v) | none |
| reads a struct | &T | f(&config) | none |
| modifies in place | &mut T | f(&mut v) | none |
| keeps the value (stores it, sends it to a thread) | T | f(nom) or f(nom.clone()) | only if the caller clones |
The last row matters: when the function really needs to own, taking T by value is the right choice. The caller then decides whether to give its value away or keep a copy.
Cow: only copy when needed
One case remains that neither &str nor String covers well: a function that most often returns its input as is, and sometimes a modified version. For example, replacing spaces with underscores:
fn toujours(s: &str) -> String {
s.replace(' ', "_")
}This version allocates on every call, even when the input contains no space. Cow (clone on write) lets you return one or the other:
use std::borrow::Cow;
fn si_besoin(s: &str) -> Cow<'_, str> {
if s.contains(' ') {
Cow::Owned(s.replace(' ', "_"))
} else {
Cow::Borrowed(s)
}
}
fn variante(c: &Cow<'_, str>) -> &'static str {
match c {
Cow::Borrowed(_) => "Borrowed",
Cow::Owned(_) => "Owned",
}
}
fn main() {
let lot = ["ada", "grace hopper", "linus"];
let avant = allocs();
for s in lot {
let _propre = toujours(s);
}
let n_string = allocs() - avant;
let mut n_cow = 0;
for s in lot {
let avant = allocs();
let propre = si_besoin(s);
let n = allocs() - avant;
n_cow += n;
println!("{propre:<12} {:<8} {n}", variante(&propre));
}
println!("String : {n_string} allocations");
println!("Cow : {n_cow} allocation");
}ada Borrowed 0
grace_hopper Owned 1
linus Borrowed 0
String : 3 allocations
Cow : 1 allocationThere is nothing magic about Cow: it is an enum with two variants.
Cow<'a, str>
├─ Borrowed(&'a str) a borrow of the input 0 allocations
└─ Owned(String) a new String 1 allocationThe caller does not need to know which one it received. A Cow<str> reads like a &str: propre.len(), println!("{propre}") and every method of str work on both variants.
to_mut: the copy at the moment of writing
A borrowed Cow can become owned later. to_mut() gives write access, and makes the copy if it has not happened yet:
fn main() {
let mut c: Cow<'_, str> = Cow::Borrowed("ada");
println!("avant : {} ({c})", variante(&c));
let avant = allocs();
c.to_mut().make_ascii_uppercase();
let n = allocs() - avant;
println!("après : {} ({c})", variante(&c));
println!("to_mut : {n} allocation");
let avant = allocs();
c.to_mut().make_ascii_lowercase();
let n = allocs() - avant;
println!("encore : {} ({c}), {n} allocation", variante(&c));
}avant : Borrowed (ada)
après : Owned (ADA)
to_mut : 1 allocation
encore : Owned (ada), 0 allocation(avant is before, après after, encore again.) The first to_mut() finds a Borrowed: it allocates, copies, and the value becomes Owned. The second already finds an Owned and allocates nothing. The copy happens only once, at the first write.
A consequence worth knowing: calling to_mut() without checking whether there is anything to change cancels the whole benefit, since every borrowed value is then copied. The test has to come first.
clone on a reference
Last trap: a .clone() that does not clone what you think.
struct Config {
nom: String,
}
fn main() {
let c = Config { nom: String::from("prod") };
let r = &c;
let d = r.clone();
println!("{}", d.nom);
}warning: call to `.clone()` on a reference in this situation does nothing
--> noop.rs:8:14
|
8 | let d = r.clone();
| ^^^^^^^^
|
= note: the type `Config` does not implement `Clone`, so calling `clone` on `&Config` copies the reference, which does not do anything and can be removed
= note: `#[warn(noop_method_call)]` on by defaultConfig is not Clone. But shared references are Copy, hence Clone: the call compiles by cloning the reference. d is a second &Config, not a Config. The program does print prod, and no copy of the configuration exists.
If the result has to be an owned value, the same cause becomes an error:
fn dupliquer(c: &Config) -> Config {
c.clone()
}error[E0308]: mismatched types
--> reft.rs:6:5
|
5 | fn dupliquer(c: &Config) -> Config {
| ------ expected `Config` because of return type
6 | c.clone()
| ^^^^^^^^^ expected `Config`, found `&Config`
|
note: `Config` does not implement `Clone`, so `&Config` was cloned instead
--> reft.rs:6:5
|
6 | c.clone()
| ^
help: consider annotating `Config` with `#[derive(Clone)]`
|
1 + #[derive(Clone)]
2 | struct Config {
|In both cases, the fix is #[derive(Clone)] on the type. In generic code, the shape is the same: a function that clones a &T must ask for T: Clone.
What the picture hides
- Cloning is sometimes the right move. When the value really has to exist twice (a copy for another thread, a value stored in a struct that lives longer), the clone is the correct answer. On a small value, in code that runs once at startup, its cost cannot be measured. The problem is the clone written by reflex on a path that runs millions of times.
to_owned(),to_string()andString::fromare the same family. Applied to a&str, they all allocate aString. They are not calledclone, but they count the same.Cowhas a price. Each access tests the variant, the signature carries a lifetime, and the type spreads to the callers. If the function always modifies its input, return aString; if it never does, return a&str.Cowis only justified for the mixed case, on a path where the allocation matters.Cowis not limited to strings.Cow<[T]>does the same between&[T]andVec<T>, and more generallyCow<B>between&Band its owned version.Rcbehaves likeArc.Rc::cloneincrements a counter without copying anything.Rc::make_mutandArc::make_mutapply the same idea asto_mut: they only clone the content if it is shared.- An allocation is more than a copy. It goes through the allocator, which has to find a free block and later take it back. On a hot path, that work, more than the copying of the bytes, is often what costs.
- Measure before fixing. The allocation counter in this article is twenty lines long and tells you where the program allocates. That is more reliable than rereading the code looking for
.clone().
Going further
- Volume 9, issue 02 of The Rust Loop, clone, Cow & the hidden allocation, which starts from the clone written to silence the compiler and goes all the way to choosing between
String,&strandCow(link at the bottom of the page). - Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369), dyn and the vtable (E0038), the orphan rule (E0117), Box and recursive types (E0072), Rc and Arc (E0277), Cell and RefCell, threads and move (E0373), Send, Sync andArc<Mutex<T>>(E0277), mpsc channels (E0382), Future and .await (E0728), colored functions and Send, cancel and select, iterators. - The
Cowdocumentation, withto_mutandinto_owned - The
Clonetrait and theCopytrait, which spells out which types can beCopy - The Rust Book, chapter 4.1: ownership, for the stack, the heap and moves
- The
Arcdocumentation, which explains theArc::clone(&x)convention