diff --git a/absl/strings/string_view.h b/absl/strings/string_view.h index 68b90aa31..841570b67 100644 --- a/absl/strings/string_view.h +++ b/absl/strings/string_view.h @@ -168,7 +168,9 @@ class string_view { string_view( // NOLINT(runtime/explicit) const std::basic_string, Allocator>& str) noexcept - : ptr_(str.data()), length_(CheckLengthInternal(str.size())) {} + // This is implement in terms of `string_view(p, n)` so `str.size()` + // doesn't need to be reevaluated after `ptr_` is set. + : string_view(str.data(), str.size()) {} // Implicit constructor of a `string_view` from nul-terminated `str`. When // accepting possibly null strings, use `absl::NullSafeStringView(str)` diff --git a/absl/strings/string_view_benchmark.cc b/absl/strings/string_view_benchmark.cc index 46909cb09..f2e4214c5 100644 --- a/absl/strings/string_view_benchmark.cc +++ b/absl/strings/string_view_benchmark.cc @@ -30,6 +30,24 @@ namespace { +void BM_StringViewFromString(benchmark::State& state) { + std::string s(state.range(0), 'x'); + std::string* ps = &s; + struct SV { + SV() = default; + explicit SV(const std::string& s) : sv(s) {} + absl::string_view sv; + } sv; + SV* psv = &sv; + benchmark::DoNotOptimize(ps); + benchmark::DoNotOptimize(psv); + for (auto _ : state) { + new (psv) SV(*ps); + benchmark::DoNotOptimize(sv); + } +} +BENCHMARK(BM_StringViewFromString)->Arg(12)->Arg(128); + // Provide a forcibly out-of-line wrapper for operator== that can be used in // benchmarks to measure the impact of inlining. ABSL_ATTRIBUTE_NOINLINE