5

I recently learned about std::string_view and how it is much faster than allocating strings so I am trying to use this in place of std::string where possible.

Is there a way of optimizing a loop that parses a file line by line to use std::string_view instead?

This is the code I am working on.

    std::string line;

    // loop until we find the cabbage tag
    while (std::getline(csd, line))
    {
        //DO STUFF
        if (line.find("</STOP>") != std::string::npos)
            break;
    }
2
  • 1
    You still need an std::string to own the data (getline just reads characters from a stream and needs to put them somewhere). But you can create a view simply with std::string_view lineView = line; and go from there for parsing. Commented Nov 9, 2020 at 15:17
  • 1
    For getline you need std::string anyway, then you might use string_view for find but it doesn't make sense to me - it will not speed up anything. Commented Nov 9, 2020 at 15:18

2 Answers 2

4

What you're looking for is mmap, that allows you to read into a file's data without copying them. Reading from a stream in C++ will always copy the data. You can then, of course, use std::string_view to point at the data revealed by mmap, and do all operations you like.

Sign up to request clarification or add additional context in comments.

1 Comment

mmap is for posix system, in windows there's CreateFileMapping
1

No. A string_view is:

  • A constant view into some storage, so you can't read into the string_view
  • Does not own the storage, but instead "refers" to some other storage, so there's nowhere for getline to put the information that it reads.

However, once you read the data into a string, you can make a string_view and pass that to a routine for parsing (avoiding passing a copy in that case).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.