I wasn't exactly sure how to formulate this question. I think it is easier to show with an example.
Say I have the following strings in my code:
std::string str1 = "Wild_Dog";
std::string str2 = "Wild_Cat";
std::string str3 = "Wild_Human";
std::string str4 = "Wild_Goblin";
std::string str5 = "Wild_Dragon";
Is there any reason other than coding style to instead write the code like this?
std::string prefix = "Wild_";
std::string str1 = prefix + "Dog";
std::string str2 = prefix + "Cat";
std::string str3 = prefix + "Human";
std::string str4 = prefix + "Goblin";
std::string str5 = prefix + "Dragon";
(Note: there is no other variable instead of wild_***, so it will always be the same prefix)
"Wild"
. When you want to change it to"Tamed"
you want to change it in one place only) vs performance (dont create unnecessary temporary strings). Without more context it is impossible to decide. In general write code for readability, not to save memory or a couple of cpu cycles.prefix
aconstexpr const char*
(We can't createconstexpr std::string
). So the compiler will probably just create your first code above and you will nonetheless DRY.