为什么当编译器知道长度时不优化字符串分配? [英] Why isn't string assignment optimised when the length is known to the compiler?

查看:96
本文介绍了为什么当编译器知道长度时不优化字符串分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天正在玩一些时间代码,发现当将一个字符串字面量定为std :: string时,它的速度快了10%(用一个短的12个字符串,因此对于大字符串来说,甚至更大的区别)用一个已知长度的文字(使用sizeof运算符)来做到这一点。 (只用VC9编译器测试,所以我想其他编译器可能做得更好)。

  std :: string a你好,世界!); 
std :: string b(Hello World!,sizeof(Hello World!); //在我的测试中快10%

现在我怀疑的原因是它已经调用strlen(VC9进入程序集,这是我的一个强点,所以我不能100%确定)以获取字符串长度



给定std :: string的长度,以及第一种情况有多常见(特别是如果你包括+,=,+ =,等等操作符和等价方法)在现实世界程序中如何进行优化第一种情况进入第二?似乎一个非常简单的,只是说如果它是一个std :: basic_string对象

解决方案

第一个不能在第一个,字符串的长度是未知的,因此必须计算,在第二个你告诉它多长,因此不需要计算。



并且使用sizeof()没有什么区别 - 这是在编译时计算。第一种情况使用的构造函数是:

  string(const char * s); 

这个构造函数没有办法检测到它被赋予一个字符串字面量,在编译时。



此外,从C风格的字符串字面构造字符串在实际代码中相对很少发生 - 它根本不值得优化。如果你需要优化它,只需重写:

  while(BIGLOOP){
string s foobar);
...
}

as:

  string f(foobar); 
while(BIGLOOP){
string s(f);
...
}


I was playing around today with some timing code and discovered that when asigning a string literal to std::string, that it was around 10% faster (with a short 12 char string, so likly even bigger difference for large strings) to do so with a literal of known length (using the sizeof operator) than not. (Only tested with the VC9 compiler, so I guess other compilers may do it better).

std::string a("Hello World!");
std::string b("Hello World!", sizeof("Hello World!");//10% faster in my tests

Now the reason I suspect is for a it has to call strlen (VC9 goes into assembly which isnt a strong point of mine so I cant be 100% sure) to get the string length, then do the same as the second case does anyway.

Given how long std::string has been around, and how common the first case is (especially if you include +, =, +=, etc operators and equivalent methods) in real world programs how come it doesn't optimise the first case into the second? It seems a really simple one as well to just say if it's an std::basic_string object and a literal, compile it as if it was written like b?

解决方案

The first can't be optimised into the second. In the first, the length of the string is unknown and so has to be calculated, in the second you tell it how long it is, so no calculation is needed.

And using sizeof() makes no difference - that is calculated at compile time too. The constructor that the first case uses is:

 string( const char * s );

there is no way of this constructor detecting it is being given a string literal, much less calculating its length at compile time.

Also, constructing strings from C-style string literals happens relatively rarely in real code - it simply isn't worth optimising. And if you do need to optimise it, simply re-write:

while( BIGLOOP ) {
   string s( "foobar" );
   ...
}

as:

string f( "foobar" );
while( BIGLOOP ) {
   string s( f );
   ...
}

这篇关于为什么当编译器知道长度时不优化字符串分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆