C++ String length() 和 size() 哪个更快?
Which is faster C++ String length() or size()?
length()
returns 字符串中的字符数和 size()
returns 一个 size_t
这也是相同的但用于使其保持一致与其他 STL 容器一起使用。
为了计算length()
,字符串遍历所有字符并计算长度。所以,O(n)
次。
size()
也一样吗?
或者可以在 O(1)
时间内直接计算变量的大小吗?
所以,我的问题是,它们在速度方面是否相同(如它们的计算方式)或大小是否在 O(1)
时间内计算?
两者具有相同的复杂性:常量。
来自 N4431 工作草案,§21.4.4
size_type size() const noexcept;
Returns: A count of the number of char-like objects currently in the string. Complexity: Constant time.
和
size_type length() const noexcept;
Returns: size().
[...] iterates through all the characters and counts the length [...]
这就是您正在考虑的 C 字符串。
如果您查看文档 here,它说 length
和 size
是相同的。
Both string::size and string::length are synonyms and return the same value.
此外,如果您查看代码,长度会被缓存,因此复杂度为 O(1)
。 (来自 MS 实现的代码,但我确信其他库也以相同的方式完成。)
size_type length() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize);
}
size_type size() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize);
}
它们是等价的。另外,字符串在返回大小时不计算字符,那是 char 数组,如果字符串总是计算字符那么它们会太慢。
C++ 中字符串的两个函数完全相同,Returns 字符串中的字符数,不包括任何 null 终止符。
length()
returns 字符串中的字符数和 size()
returns 一个 size_t
这也是相同的但用于使其保持一致与其他 STL 容器一起使用。
为了计算length()
,字符串遍历所有字符并计算长度。所以,O(n)
次。
size()
也一样吗?
或者可以在 O(1)
时间内直接计算变量的大小吗?
所以,我的问题是,它们在速度方面是否相同(如它们的计算方式)或大小是否在 O(1)
时间内计算?
两者具有相同的复杂性:常量。
来自 N4431 工作草案,§21.4.4
size_type size() const noexcept;
Returns: A count of the number of char-like objects currently in the string. Complexity: Constant time.
和
size_type length() const noexcept;
Returns: size().
[...] iterates through all the characters and counts the length [...]
这就是您正在考虑的 C 字符串。
如果您查看文档 here,它说 length
和 size
是相同的。
Both string::size and string::length are synonyms and return the same value.
此外,如果您查看代码,长度会被缓存,因此复杂度为 O(1)
。 (来自 MS 实现的代码,但我确信其他库也以相同的方式完成。)
size_type length() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize);
}
size_type size() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize);
}
它们是等价的。另外,字符串在返回大小时不计算字符,那是 char 数组,如果字符串总是计算字符那么它们会太慢。
C++ 中字符串的两个函数完全相同,Returns 字符串中的字符数,不包括任何 null 终止符。