about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--absl/strings/string_view.h4
-rw-r--r--absl/strings/string_view_benchmark.cc18
2 files changed, 21 insertions, 1 deletions
diff --git a/absl/strings/string_view.h b/absl/strings/string_view.h
index 68b90aa3126f..841570b6713e 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<char, std::char_traits<char>, 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 46909cb093d4..f2e4214c5110 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