简体   繁体   English

Cpp核心指南在这个例子中浪费了什么?

[英]What is wasted in this example from the Cpp Core Guidelines?

What is wasted in the example from the Cpp Core Guidelines? Cpp核心指南中的例子浪费了什么?

P.9: Don't waste time or space P.9:不要浪费时间或空间

[...] [...]

 void lower(zstring s) { for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } 

Yes, this is an example from production code. 是的,这是生产代码的一个例子。 We leave it to the reader to figure out what's wasted. 我们留给读者来弄清楚浪费了什么。

from https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rp-waste 来自https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rp-waste

strlen在循环的每次迭代中计算。

每次检查循环条件时都会调用strlen ,每次调用需要O(n)次,因此循环的总时间为O(n ^ 2)。

A lot of time is wasted and a segmentation fault may occur as the author of the code's increasing s , not i in the loop: 浪费了大量的时间,并且当代码的作者增加s可能会发生分段错误,而不是循环中的i

for (int i = 0; i < strlen(s); ++s)
                 //right here ^^^^

As other aswers have already stated, strlen(s) is called multiple times because it is in the condition, implying that it should be cached and reused instead. 正如其他的aswers已经说过的那样, strlen(s)被多次调用,因为它处于这种状态,这意味着它应该被高速缓存并重新使用。

But strlen(s) does not actually need to be called at all ! 但实际上并不需要调用strlen(s) s is (or is implicitly convertible to) a nul-terminated char array, since that's what strlen expects. s是(或者可以隐式转换为)以nul结尾的char数组,因为这是strlen期望的。 So we can just use this very property for our own loop. 所以我们可以将这个属性用于我们自己的循环。

void lower(zstring s) {
    for (char *p = s; *p; ++p)
        *p = std::tolower((unsigned char)*p);
}

Unless they have any very unintuitive semantics in the zstring class, the function in it's current form is a complete waste of both time and space, as its "result" can't be used after the function - it is passed in as value, and isn't returned. 除非它们在zstring类中有任何非直观的语义, zstring它当前形式的函数完全浪费时间空间,因为它的“结果”不能在函数之后使用 - 它作为值传入,并且不归还。

So to avoid wasting the time to uselessly compute the lowercase which can't be used, and the space in copying the passed parameter, I would pass by reference! 所以为了避免浪费时间无用地计算不能使用的小写,以及复制传递参数的空间,我会通过引用传递!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM