0

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)

3
  • 3
    It depends a bit on what you want to do with the strings. It won't save you any memory. It even could be a bit slower since you create a temporary (but maybe the compiler optimizes that). Personally I think coding style alone is a good enough reason to do it that way^^
    – n314159
    Nov 25, 2019 at 13:47
  • 3
    there are arguments for either options: DRY (dont repeat "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. Nov 25, 2019 at 13:49
  • 1
    I am not exactly sure, but maybe it would be a bit better to make prefix a constexpr const char* (We can't create constexpr std::string). So the compiler will probably just create your first code above and you will nonetheless DRY.
    – n314159
    Nov 25, 2019 at 14:15

1 Answer 1

1

I think, I overengineered that a bit: https://godbolt.org/z/x4wf5r. This should have both the best possible performance and also has the prefix only specified once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.