0

I have a variable that's guaranteed to be a single character (substr from a std::string).

I strongly suspect that it's more efficient to use a char, i.e.

char c = name.c_str()[offset];

instead of the more complicated (and costly)

std::string c = name.substr(offset, 1);

I'm not going to do any intensive operations on the resulting character (just one switch statement).

Gotcha
  • 25
  • 1
  • 5
  • 3
    You can just do `char c = name[offset];` in that first example. – Blastfurnace May 22 '15 at 03:45
  • depends on your definition of "character" if you are talking about single byte, you'll be fine. If you are talking about single unicode character in UTF-8 string, then you won't. – n0rd May 22 '15 at 03:51
  • 1
    You could just switch on `name[offset]` if you wanted to. – Retired Ninja May 22 '15 at 03:54
  • 2
    If you want to do a `switch()` statement then you have to use a `char` because you can't use `switch()` with `std::string`. – Galik May 22 '15 at 04:05
  • @Blastfurnace unless offset is allowed to indicate the null terminator – M.M May 22 '15 at 04:32
  • 1
    To make this decision you would take into account what you're doing with it later. Using `char` to store a single character makes the most sense, in a vacuum. – M.M May 22 '15 at 04:33
  • @Blastfurnace, noted. I couldn't find any mention of it in the documentation. @Galik, if I used a `std::string` then I would have used a `if-else` chain. – Gotcha May 22 '15 at 15:22

1 Answers1

1

It is probably better to use a char in this case, assuming you want to store it and process it often latter, otherwise you can just directly access the string individual chars using operator[]. One thing to note is that std::string implements the so-called short string optimization, which should be quite fast. But anyway, you should profile your code, and unless you need a std::string (e.g. to be passed around latter in some other functions), you should just use a char.

Community
  • 1
  • 1
vsoftco
  • 52,188
  • 7
  • 109
  • 221