Skip to content

Commit a798a10

Browse files
authored
[libc++] Optimize vector<bool>(const vector<bool>&) (#161672)
``` Benchmark Baseline Candidate Difference % Difference ------------------------ ---------- ----------- ------------ -------------- BM_vector_bool_copy_ctor 56.93 10.93 -46.00 -80.80 BM_vector_bool_size_ctor 7.99 8.01 0.02 0.22 ```
1 parent b717f83 commit a798a10

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

libcxx/include/__vector/vector_bool.h

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
#include <__algorithm/copy.h>
1313
#include <__algorithm/copy_backward.h>
14+
#include <__algorithm/copy_n.h>
1415
#include <__algorithm/fill_n.h>
1516
#include <__algorithm/iterator_operations.h>
1617
#include <__algorithm/max.h>
@@ -701,7 +702,8 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 vector<bool, _Allocator>::vector(const vector& __v
701702
__alloc_(__storage_traits::select_on_container_copy_construction(__v.__alloc_)) {
702703
if (__v.size() > 0) {
703704
__vallocate(__v.size());
704-
__construct_at_end(__v.begin(), __v.end(), __v.size());
705+
std::copy_n(__v.__begin_, __external_cap_to_internal(__v.size()), __begin_);
706+
__size_ = __v.size();
705707
}
706708
}
707709

@@ -710,7 +712,8 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 vector<bool, _Allocator>::vector(const vector& __v
710712
: __begin_(nullptr), __size_(0), __cap_(0), __alloc_(__a) {
711713
if (__v.size() > 0) {
712714
__vallocate(__v.size());
713-
__construct_at_end(__v.begin(), __v.end(), __v.size());
715+
std::copy_n(__v.__begin_, __external_cap_to_internal(__v.size()), __begin_);
716+
__size_ = __v.size();
714717
}
715718
}
716719

@@ -723,7 +726,7 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 vector<bool, _Allocator>& vector<bool, _Allocator>
723726
__vdeallocate();
724727
__vallocate(__v.__size_);
725728
}
726-
std::copy(__v.__begin_, __v.__begin_ + __external_cap_to_internal(__v.__size_), __begin_);
729+
std::copy_n(__v.__begin_, __external_cap_to_internal(__v.size()), __begin_);
727730
}
728731
__size_ = __v.__size_;
729732
}

libcxx/test/benchmarks/containers/sequence/vector_bool.bench.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@
99
#include <benchmark/benchmark.h>
1010
#include <vector>
1111

12+
static void BM_vector_bool_copy_ctor(benchmark::State& state) {
13+
std::vector<bool> vec(100, true);
14+
15+
for (auto _ : state) {
16+
benchmark::DoNotOptimize(vec);
17+
std::vector<bool> vec2(vec);
18+
benchmark::DoNotOptimize(vec2);
19+
}
20+
}
21+
BENCHMARK(BM_vector_bool_copy_ctor);
22+
1223
static void BM_vector_bool_size_ctor(benchmark::State& state) {
1324
for (auto _ : state) {
1425
std::vector<bool> vec(100, true);

0 commit comments

Comments
 (0)