Eeshaan
Eeshaan

Reputation: 1635

String fundamentals

So far I know the following ways to have strings in C++ (although some of these are from C)

string string1 = "Hello";
char string2[] = "Hello";
char string3[] = {'H', 'e', 'l', 'l', 'o', 0};
const char *string4 = "Hello";
  1. I find the first method to be the most convenient as it supports several methods and has overloaded operators. But I believe that also makes it the least optimized in terms of performance, is that so?
  2. Which method is the best in terms of performance / speed?
  3. Which of these are allocated on stack and which on heap? I mean I don't see any new keyword, but then my intuition says otherwise.

Upvotes: 0

Views: 77

Answers (1)

Waqar
Waqar

Reputation: 9331

I find the first method to be the most convenient as it supports several methods and has overloaded operators.

Correct. And it should be the default way you should handle strings in C++.

But I believe that also makes it the least optimized in terms of performance, is that so?

Least optimized? For what? As far as a normal application is concerned, std::string is very fast. It is heavily optimized for many many use cases. A large number of very smart people work very hard to make sure it is fast. Take a look at this SO question where someone tries to implement one of the std::string operations themselves but is unable to beat std::string performance.

Which method is the best in terms of performance / speed?

std::string is the fastest. Before you say it's not, think how you are going to use your strings. Are you doing any of the following?

  • Comparing
  • Concatenation
  • Passing strings around in functions
  • searching

std::string can do all these very quickly. However, if you end up using const char* or the char array, you will have to do these operations manually which will almost certainly be slower than the std::string implementation. Not to mention the various pointer and memory issues you will have to tackle.

Which of these are allocated on stack and which on heap? I mean I don't see any new keyword, but then my intuition says otherwise.

All of the strings you showed are on stack, even std::string. std::string has SSO(short string optimization) built-in which stores short strings on the stack.

Upvotes: 3

Related Questions