ARandomFurry
ARandomFurry

Reputation: 203

Efficient Way to Read from ifstream to stringstream

I have this function:

void GetLine(std::stringstream &output,std::ifstream &input,char C){
    static std::string Line;
    std::getline(input,Line,C);
    output.str(Line);
}

How can I make it more efficient as to not copy the data more times that I have to.

Edit: Removed static to simplify code, fixed syntax error. No error checking is done because it doesn't need to be done inside this function.

Upvotes: 3

Views: 669

Answers (1)

user633206
user633206

Reputation: 81

Yout main performance problem isn't copying, it's memory allocation. Assuming you actually removed the static, your stirng object is located in stack memory, but the string data in located in memory dynamicallty allocated on the heap. Since you are constructing your string operation each time, you have one or more dynamic allocations and a free for each line copied. These are very expensive allocations.

Making the string static will help with timing at the expense of memory. In most library implementations, getline will not change the amount of memory allocated to hold string data. So the string buffer will expand to the size of the largest string read from the file and stay there. But since the string object is static you have no way to release this memory. There are other ways to structure the program that can resolve this problem.

If this piece of code is really the hold-up in your code (how do you know it is?), and your input has a maximum line length, then don't use a std::string and use istream::getline to read into a character array. This will set a error in the ifstream if you encounter a line longer than your buffer. Inserting into a character array is faster tha inserting into a string. However, I'd be surprised if this code is really taking that much time.

Upvotes: 2

Related Questions