C++ string库 resize坑

#include <sys/time.h>

int main()
{
  string str1;
  string str2;
  str1.resize(100000000);
  unsigned long realtime;
  struct timeval ts;
  unsigned long timecount;
  gettimeofday(&ts, NULL);

  timecount = ts.tv_sec * 1000 + ts.tv_usec / 1000;

  cout << "init time:" << timecount << endl;
  for (size_t i = 0; i < 100000000; i++)
  {
    str1.append("1");
  }
  gettimeofday(&ts, NULL);
  realtime = ts.tv_sec * 1000 + ts.tv_usec / 1000;

  cout << "time2:" << realtime - timecount << endl;
  timecount = realtime;

  for (size_t i = 0; i < 100000000; i++)
  {
    str2.append("1");
  }
  gettimeofday(&ts, NULL);
  realtime = ts.tv_sec * 1000 + ts.tv_usec / 1000;
  cout << "time3:" << realtime - timecount << endl;

  // resize() 垃圾方法  没啥用
}
  • 输出值
    init time:1576488420443
    time2:787
    time3:792

结论:
看出来了没有不论是否resize()字符串数组大小,然后append速度都是一样的。
所以认为resize()后性能会很好,会很棒棒的人,就别这样做了,
不仅不会优化性能还会降低以及后面一连串错误,比如c_str(),data()不能达到预期。

原因
具体我也不了解,这个和vector容器,以及string的机制有关。
并且如果string当前的size()小于resize()值 之后,c_str()返回的会是一个空值,
data()方法也不能返回预期的值。
原因是resize()后会重新分配一份内存,
c_str()返回的依然是旧内存的地址(可能),
有人误人子弟说这时该data()方法来获取,我试了也不行。

在string上resize方法的解释:

 Resizes the %string to the specified number of characters.
       *  @param  __n  Number of characters the %string should contain.
       *
       *  This function will resize the %string to the specified length.  If
       *  the new size is smaller than the %string's current size the %string
       *  is truncated, otherwise the %string is extended and new characters
       *  are default-constructed.  For basic types such as char, this means
       *  setting them to 0.

具体就是说resize,如果当前resize值大于当前字符串size()值,就会增加字符串的长度,然后调用append是在新增长度末尾增加的,实际测得确实如此.
如果小于当前值,就是截断当前字符串.

最后强烈建议还是别用resize() 缺点太多未知隐患太多,不是很懂能不用就不用.

发布了148 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44580977/article/details/103566606