I have a simple scenario. I need to join two C-strings together into a std::string. I have decided to do this in one of two ways:
Solution 1
void ProcessEvent(char const* pName) {
std::string fullName;
fullName.reserve(50); // Ensure minimal reallocations for small event names (50 is an arbitrary limit).
fullName += "com.domain.events.";
fullName += pName;
// Use fullName as needed
}
Solution 2
void ProcessEvent(char const* pName) {
std::ostringstream ss;
ss << "com.domain.events." << pName;
std::string fullName{ss.str()};
// Use fullName as needed
}
I like solution 2 better because the code is more natural. Solution 1 seems like a response to a measurable bottleneck from performance testing. However, Solution 1 exists for 2 reasons:
- It's a light optimization to reduce allocations. Event management in this application is used quite frequently so there might be benefits (but no measurements have been taken).
- I've heard criticism regarding STL streams WRT performance. Some have recommended to only use stringstream when doing heavy string building, especially those involving number conversions and/or usage of manipulators.
Is it a premature pessimization to prefer solution 2 for its simplicity? Or is it a premature optimization to choose solution 1? I'm wondering if I'm too overly concerned about STL streams.
std::stringwould not the most optimal solution either.reserve()for this situation. I usually only think of usingstd::stringstreamswhen I need to convert numbers or user defined types. Although you should not prematurely optimize, I think you should still be mindful of efficiency.std::string fullName = std::string{"com.domain.events."} + std::string{pName};-- There are many ways to skin this cat. Keep things simple when you can.std::string fullName = "com.domain.events."s + pName;. About as simple as you can get.