Skip to content

Commit 7a00c27

Browse files
Optimize Option::clone to Copy when possible
Prior to this change, cloning an Option value would branch on whether the Option was Some, even if it would be cheaper to just memcpy the bits. Default the current implementation, and then specialize it for Copy types, to avoid the branch.
1 parent 97eb606 commit 7a00c27

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

library/core/src/option.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -1228,22 +1228,35 @@ fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
12281228
#[stable(feature = "rust1", since = "1.0.0")]
12291229
impl<T: Clone> Clone for Option<T> {
12301230
#[inline]
1231-
fn clone(&self) -> Self {
1231+
default fn clone(&self) -> Self {
12321232
match self {
12331233
Some(x) => Some(x.clone()),
12341234
None => None,
12351235
}
12361236
}
12371237

12381238
#[inline]
1239-
fn clone_from(&mut self, source: &Self) {
1239+
default fn clone_from(&mut self, source: &Self) {
12401240
match (self, source) {
12411241
(Some(to), Some(from)) => to.clone_from(from),
12421242
(to, from) => *to = from.clone(),
12431243
}
12441244
}
12451245
}
12461246

1247+
#[stable(feature = "rust1", since = "1.0.0")]
1248+
impl<T: Copy> Clone for Option<T> {
1249+
#[inline]
1250+
fn clone(&self) -> Self {
1251+
*self
1252+
}
1253+
1254+
#[inline]
1255+
fn clone_from(&mut self, source: &Self) {
1256+
*self = *source
1257+
}
1258+
}
1259+
12471260
#[stable(feature = "rust1", since = "1.0.0")]
12481261
impl<T> Default for Option<T> {
12491262
/// Returns [`None`][Option::None].

0 commit comments

Comments
 (0)