2

在 c++ stl 库的上下文中,什么表现更好 string::+= 或 sstream::<< 或者它取决于其他东西?

编辑:这是否取决于我们附加的数据大小?

4

3 回答 3

4

It depends on many various parameters, the main parameter is the implementation of these operators and compiler itself.

Just a simple test in a specific version of a compiler can be a naive observation. For example simply adding a short string 10,000,000 times to a string or istringstream and measuring the time is done here. It shows += is faster that <<.

time (ms):534.02   // For +=
time (ms):927.578  // For <<

In your real application, you should use +=, if you suspect it's slow and damaging your performance then test another one. Profiling is the keyword.

于 2013-10-31T09:14:32.983 回答
0

除了 string+= 推荐,我还要补充一点,如果你附加普通的 char* 并知道它的长度,你应该使用 string.append(data*, length) 方法,这将节省你内部的长度计算。混合 C/C++ 代码的示例,而不是

  char temp[256];
  sprintf(temp, <some insane pattern>, <some valuable data>,...);
  str += temp;

你应该使用

  char temp[256];
  const int length = sprintf(temp, <some insane pattern>, <some valuable data>,...);
  str.apeend(temp, length);
于 2013-10-31T09:31:20.130 回答
-3

编辑:建议一般使用 string::+= 和 sstream::<< 当您知道附加字符串很大时。

于 2013-10-31T09:22:54.447 回答