sstream vs for loop speed for processing a string

178 Views Asked by At

I was wondering wether sstream is faster than just a for loop for processing a string? say for example we have a string that we can't to separate just the words:

std::string somestring = "My dear aunt sally went to the market and couldn't find what she was looking for";

would a string stream be faster? Its definitely prettier.

std::string temp;
stringstream input(somestring);
while(input >> temp){
  std::cout << temp;
}

or utilizing a regular old for loop and a buffer?

std::string buffer; //word buffer
    for(int i= 0; i < somestring.size(); ++i){
        if(somestring.at(i) == 32 && buffer == ""){
            continue;
        }
        if(somestring.at(i) == 32 || somestring.at(i) == '\n'){
            std::cout << buffer;
            buffer.clear();
            continue;
        }
        buffer += somestring.at(i);
    }
    std::cout << buffer;

tldr: I guess i'm mainly wondering if sstream is more optimized and faster at processing a string than just a regular for loop?

EDIT: Edited the forloop

1

There are 1 best solutions below

0
Vlad Feinstein On

You tagged your question with performance, but you didn't specify the details of "processing a string".

Do you need to copy the words to a different storage? Or just to identify them? In both of your examples, copying will take most of the time.

Needless to say, you should not have std::cout in performance-critical code :)