newcpp
newcpp

Reputation: 41

Efficient way to create array of string

I need to create array of string which one will be the more efficient.

1.std::array<std::string, 3>arr  {"aa", "bb", "cc"};
2.std::vector<std::string> arr = {"aa","bb","cc"};
3.string arr[3]                = {"aa", "bb", "cc"};

Note : All the string(aa,bb,cc) in my case is fixed during initialised time. please suggested any other way if any.

Upvotes: 2

Views: 474

Answers (2)

Steephen
Steephen

Reputation: 15824

I will go for 3rd one. Simple and there is no compile time or run time overhead off std::array or std::vector

string arr[3]                = {"aa", "bb", "cc"};

Upvotes: 2

ShadowRanger
ShadowRanger

Reputation: 155418

std::array<std::string, 3> arr{"aa", "bb", "cc"}; and string arr[3] = {"aa", "bb", "cc"}; should be equally performant. std::array bakes the array size into the type so it doesn't degrade to a pointer with unknown size when passed around (just make sure it's passed around by reference to avoid copies), and has more C++ utility methods, but otherwise has the same performance and behavior characteristics as C arrays, so it's probably the way to go.

If you can use C++14, a very small improvement could be made by making the strings std::string literals, which allows them to be converted from C-style strings to std::string slightly more efficiently (the size is baked in at compile time, so it can use the known length constructor, rather than the one that must first scan for the NUL terminator).

using namespace std::string_literals;

std::array<std::string, 3> arr{"aa"s, "bb"s, "cc"s};  // s suffix makes them string literals

Upvotes: 4

Related Questions