refactor: Use std::string_view for prop conversions#43218
refactor: Use std::string_view for prop conversions#43218Saadnajmi wants to merge 2 commits intofacebook:mainfrom
std::string_view for prop conversions#43218Conversation
packages/react-native/ReactCommon/react/renderer/components/view/conversions.h
Outdated
Show resolved
Hide resolved
Co-authored-by: Tommy Nguyen <4123478+tido64@users.noreply.github.com>
Base commit: 57ed0fb |
motiz88
left a comment
There was a problem hiding this comment.
Hey @Saadnajmi! These all seem like instances of the same, sadly invalid, pattern - see my comment on the first one.
|
|
||
| static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, EnumPropNativeComponentViewAlignment &result) { | ||
| auto string = (std::string)value; | ||
| auto string = std::string_view{(std::string)value}; |
There was a problem hiding this comment.
Casting to string and then to string_view doesn't really make sense, I'm afraid. You're creating a temporary string (incurring the same copy as before btw), then effectively creating a dangling pointer to its contents. See proof by godbolt + asan.
I don't have enough context, but it might make sense to create a non-copying const string& / string_value accessor on RawValue, if we know the string is stored in some stable location that is safe to access for the life of our value reference.
There was a problem hiding this comment.
Ah, that makes sense. I had assumed we were casting from an any-ish type and the conversion was "free". std::string_view accepts raw char*, would it be enough to drop the cast i.e., auto string = string_view{value};?
Edit: Nvm, it looks like the string conversion is handled by the underlying folly::dynamic instance. Implementing a RawValue::string_view method using its dynamic::c_str() seems possible? Sorry, on mobile so it's hard to do proper investigation.
There was a problem hiding this comment.
TIL I learned about compiler explorer, pretty awesome!
OK, I'll keep this PR up a bit to explore an alternative path, but noted the current version is not what we want.
|
Closing as I don't expect to come back to this |
Summary:
As pointed out by @tido64 in one of my other PRs, we can be more efficient on prop conversions by using
std::string_viewinstead of just casting to std::string, which may cause a copy. I thought I might as well do a Find+Replace for the whole codebase and see what breaks.Changelog:
[GENERAL] [CHANGED] - Use
std::string_viewfor prop conversionsTest Plan:
CI should pass