[PATCH] D129533: [ADT] Pass string_view via copy in twine

ppenguin via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Thu Jul 21 20:15:45 PDT 2022


prehistoric-penguin updated this revision to Diff 446699.
prehistoric-penguin added a comment.

Take the cheap object std::string_view by copy is the preferred way:

They have performance differences, pass by reference has one more level
of indirection, so we need one more instruction when compared with the
copy way For such code snippet(https://godbolt.org/z/19rWfd96W):

  void TakesStringViewByValue(std::string_view s)
  {
  benchmark::DoNotOptimize(s.data());
  }
  void TakesStringViewByRef(const std::string_view& s)
  {
  benchmark::DoNotOptimize(s.data());
  }

When get the disassembly after build with -O3, pass by value will save us
one instruction:

  TakesStringViewByValue(std::basic_string_view<char, std::char_traits<char> >):
  movq %rsi, -8(%rsp)
  retq
  TakesStringViewByRef(std::basic_string_view<char, std::char_traits<char> > const&):
  movq 8(%rdi), %rax
  movq %rax, -8(%rsp)
  retq
  _GLOBAL__sub_I_example.cpp: # @_GLOBAL__sub_I_example.cpp
  jmp benchmark::internal::InitializeStreams()@PLT # TAILCALL

And according to the abseil c++ tips week 1(https://abseil.io/tips/1),
they also recommend us to pass std::string_view by copy:

   Unlike other string types, you should pass string_view by value just
  like you would an int or a double because string_view is a small value.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D129533/new/

https://reviews.llvm.org/D129533

Files:
  llvm/include/llvm/ADT/Twine.h


Index: llvm/include/llvm/ADT/Twine.h
===================================================================
--- llvm/include/llvm/ADT/Twine.h
+++ llvm/include/llvm/ADT/Twine.h
@@ -291,9 +291,9 @@
     /// Construct from an std::string_view by converting it to a pointer and
     /// length.  This handles string_views on a pure API basis, and avoids
     /// storing one (or a pointer to one) inside a Twine, which avoids problems
-    /// when mixing code compiled under various C++ standards.
-    /*implicit*/ Twine(const std::string_view &Str)
-        : LHSKind(PtrAndLengthKind) {
+    /// when mixing code compiled under various C++ standards. Pass string_view
+    /// by value is preferred.
+    /*implicit*/ Twine(std::string_view Str) : LHSKind(PtrAndLengthKind) {
       LHS.ptrAndLength.ptr = Str.data();
       LHS.ptrAndLength.length = Str.length();
       assert(isValid() && "Invalid twine!");


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D129533.446699.patch
Type: text/x-patch
Size: 908 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220722/7c42da21/attachment-0001.bin>


More information about the llvm-commits mailing list