# C++ string_view

> 今天遇到C++中string的性能问题，换成string_view好了一点。其实这是我第二次使用string_view，但是第一次不求甚解，这一次要查查资料。 微软的文档里说，string_view可以提高类…

- Source: https://acytoo.com/ladder/c++-string_view/
- Author: acytoo
- Published: 2021-03-04
- Updated: 2021-04-16
- Language: zh-CN
- Section: ladder
- Tags: c++

今天遇到C++中string的性能问题，换成string_view好了一点。其实这是我第二次使用string_view，但是第一次不求甚解，这一次要查查资料。

[微软的文档](https://docs.microsoft.com/en-us/cpp/standard-library/string-view?view=msvc-160)里说，string_view可以提高类string数据的读取的速度。

又看了几篇博客，string_view可以在常数时间内完成substr()操作。没有真正拷贝子字符串，而是记录指针。

后面还有一些详细的解释，我就不复制粘贴了，简单来说，string_view让C++处理字符串以及字符串片段更快，但是只读。是对C格式的指针的一种封装，直接读取某段内存。

下面是同样的逻辑实现的[LeetCode 1754](https://leetcode.com/problems/largest-merge-of-two-strings/)题，唯一的区别是，第二种方法使用string_view来接收参数。虽然LeetCode上面的算法跑的时间非常玄学，但是量级的差距还是存在的。string_view在读取子字符串时，无论是时间还是空间，优势都非常明显。

<center>
<img width="900" src="/images/screenshot_2021-03-04.png">
</center>

```cpp
class Solution {
 public:
  string largestMerge(string word1, string word2) {
    string res;
    const int m = word1.size(), n = word2.size();
    int i = 0, j = 0;
    while (i < m && j < n)
      res += word1.substr(i) > word2.substr(j) ? word1[i++] : word2[j++];
    res.append(word1.substr(i));
    res.append(word2.substr(j));
    return res;
  }
};

```

```cpp
class Solution {
 public:
  string largestMerge(string_view word1, string_view word2) {
    string res;
    const int m = word1.size(), n = word2.size();
    int i = 0, j = 0;
    while (i < m && j < n)
      res += word1.substr(i) > word2.substr(j) ? word1[i++] : word2[j++];
    res.append(word1.substr(i));
    res.append(word2.substr(j));
    return res;
  }
};
```
