Refactor: Migrate all prefs to string_view
There should be no behavioral changes, just how the parameters are
taken.
What's wrong with std::string:
1. Data is heap allocated. Most usecase of pref involves look up
some value with a compile time constant string. For example,
|prefs.GetKey(kPrefsManifestBytes)|. When this code is executed,
what it's doing is create a std::instance with kPrefsManifestBytes,
which is a const char *. The program must first determine the length
of |kPrefsManifestBytes|, allocate sufficient heap memory to store
it, then copy all contents over. After prefs.GetKey() is called, the
allocated string must be deallocated. Everytime we call GetKey()
with a const char *, we execute the same
strlen()-allocate()-copy()-deallocate() sequence. Which is not
efficient.
2. Often requires passing by reference, which introduces 1 more
pointer indirection
Why/How std::string_view fixes these problems
1. std::string_view does not own the underlying data. When you do
std::string_view{kPrefsManifestBytes}, it merely takes the pointer
in, store it, then compute the size. No heap allocation happens.
However, since std::string_view doesn't own the underlying data,
lifetime of std::string_view cannot exceed that of const char *.
This is fine for our usecase, because constants like
kPrefsManifestBytes are static constants and are valid thorugh out
the entire program execution
2. Since std::string_view is virtuall a tuple<const char *data,
size_t size>, no need to pass it by reference. It can be efficiently
passed around by value, reducing pointer indirection.
Side note:
std::string_view is essentially the C++ equivalence of go/java-tips/012
Test: th
Change-Id: I4c3f1d88a0587e36ac5eca43d553448da1e2e878
diff --git a/common/prefs_unittest.cc b/common/prefs_unittest.cc
index a5f46e5..cef6d44 100644
--- a/common/prefs_unittest.cc
+++ b/common/prefs_unittest.cc
@@ -507,8 +507,8 @@
class MockPrefsObserver : public PrefsInterface::ObserverInterface {
public:
- MOCK_METHOD1(OnPrefSet, void(const string&));
- MOCK_METHOD1(OnPrefDeleted, void(const string& key));
+ MOCK_METHOD1(OnPrefSet, void(std::string_view));
+ MOCK_METHOD1(OnPrefDeleted, void(std::string_view));
};
TEST_F(PrefsTest, ObserversCalled) {