Skip to content

Commit b7c03bb

Browse files
Optimize any::swap (#5710)
Co-authored-by: Stephan T. Lavavej <[email protected]>
1 parent 34ee4af commit b7c03bb

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

benchmarks/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ endfunction()
102102

103103
add_benchmark(adjacent_difference src/adjacent_difference.cpp)
104104
add_benchmark(adjacent_find src/adjacent_find.cpp)
105+
add_benchmark(any_swap src/any_swap.cpp)
105106
add_benchmark(bitset_from_string src/bitset_from_string.cpp)
106107
add_benchmark(bitset_to_string src/bitset_to_string.cpp)
107108
add_benchmark(efficient_nonlocking_print src/efficient_nonlocking_print.cpp)

benchmarks/src/any_swap.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3+
4+
#include <any>
5+
#include <array>
6+
#include <benchmark/benchmark.h>
7+
#include <type_traits>
8+
9+
using trivial = std::array<int, 2>;
10+
static_assert(std::is_trivially_copyable_v<trivial>);
11+
12+
struct small {
13+
std::array<int, 4> c{};
14+
small() = default;
15+
small(const small&) = default;
16+
small& operator=(const small&) = default;
17+
small(small&&) noexcept = default;
18+
small& operator=(small&&) noexcept = default;
19+
~small() {}
20+
};
21+
static_assert(!std::is_trivially_copyable_v<small>);
22+
static_assert(std::is_nothrow_move_constructible_v<small>);
23+
24+
using large = std::array<int, 32>;
25+
26+
template <class T>
27+
void bm(benchmark::State& state) {
28+
std::any a = T{};
29+
std::any b = T{};
30+
31+
for (auto _ : state) {
32+
a.swap(b);
33+
benchmark::DoNotOptimize(a);
34+
benchmark::DoNotOptimize(b);
35+
}
36+
}
37+
38+
BENCHMARK(bm<trivial>);
39+
BENCHMARK(bm<small>);
40+
BENCHMARK(bm<large>);
41+
42+
BENCHMARK_MAIN();

stl/inc/any

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,11 @@ public:
230230
}
231231

232232
void swap(any& _That) noexcept {
233-
_That = _STD exchange(*this, _STD move(_That));
233+
any _Old = _STD move(*this);
234+
reset();
235+
_Move_from(_That);
236+
_That.reset();
237+
_That._Move_from(_Old);
234238
}
235239

236240
// Observers [any.observers]

0 commit comments

Comments
 (0)