[LLVMdev] Correct use of StringRef and Twine

David Blaikie dblaikie at gmail.com
Mon Jul 18 12:38:16 PDT 2011


I'm attempting to do some amount of mass migration from const std::string&
(& const char*) to StringRef. In doing so I stumbled across the fact that
while StringRef has no op+ to speak of (well, it has += and I added a manual
StringRef+std::string and std::string+StringRef for now - though I'm
thinking perhaps they can be skipped in favor of Twine operations), Twine
does provide a variety of handy op+ implementations that get picked up
mostly for free.

A few questions from this:

* When should a StringRef parameter type be preferred over a const Twine&
parameter type?
* Would it be OK to implement an implicit conversion from Twine to
std::string rather than using the explicit str() function? (when switching
to StringRef many expressions became Twine concatenation when they were
std::string concatenation - this isn't a drop-in replacement due to the
absence of std::string conversion from Twine (which should be a perf win,
I'd think - delaying concatenation into a single operation instead of (((a +
b) + c) + d)), so I've had to wrap various concatenation expressions in
(...).str())
* What would happen if Twine gave back a pointer/reference to some internal
storage? In the common/correct use case (taking a Twine as a const ref, or
using a Twine entirely in a temporary concatenation expression) wouldn't the
Twine's internal storage live long enough to allow the caller to use that
buffer within the life of the statement (as in, say, o << (aStringRef +
"foo"))?

This last one is probably the bigger question & relates to the other two. It
seems like Twine is nice for cases where deferred concatenation is required
& might be able to be avoided altogether - if the majority case is that the
concatenation ends up being thrown away, you win. But as you approach the
100% usage (not throwing away ever) are you losing perf in the simple
non-concatenative case (all those callers who just pass in a straight string
without any concatenation - the Twine then returns that string by value when
str() is called, right?)?

At the moment, if the lifetime works out & Twine can return a reference to a
member (this would mean unrealized Twines would have a bunch of empty/spare
std::strings lying around, but I expect those could be optimized away fairly
reliably), that Twine would be strictly superior to StringRef & could be
preferred in all cases, potentially even replacing/simplifying StringRef
substantially.

Thoughts?

- David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20110718/be1f6564/attachment.html>


More information about the llvm-dev mailing list