Difference between string.empty and string[0] == '\0'

前端 未结 7 2237
迷失自我
迷失自我 2021-02-11 11:43

Suppose we have a string

std::string str; // some value is assigned

What is the difference between str.empty() and str[0] =

相关标签:
7条回答
  • 2021-02-11 12:47

    Other answers here are 100% correct. I just want to add three more notes:

    empty is generic (every STL container implements this function) while operator [] with size_t only works with string objects and array-like containers. when dealing with generic STL code, empty is preferred.

    also, empty is pretty much self explanatory while =='\0' is not very much. when it's 2AM and you debug your code, would you prefer see if(str.empty()) or if(str[0] == '\0')? if only functionality matters, we would all write in vanilla assembly.

    there is also a performance penalty involved. empty is usually implemented by comparing the size member of the string to zero, which is very cheap, easy to inline etc. comparing against the first character might be more heavy. first of all, since all strings implement short string optimization, the program first has to ask if the string is in "short mode" or "long mode". branching - worse performance. if the string is long, dereferencing it may be costly if the string was "ignored" for some time and the dereference itself may cause a cache-fault which is costly.

    0 讨论(0)
提交回复
热议问题