問題描述
我聽到一些人對 std::string 中的+"運算符和各種加速連接的解決方法表示擔憂.這些真的有必要嗎?如果是這樣,在 C++ 中連接字符串的最佳方法是什么?
I heard a few people expressing worries about "+" operator in std::string and various workarounds to speed up concatenation. Are any of these really necessary? If so, what is the best way to concatenate strings in C++?
推薦答案
額外的工作可能不值得,除非你真的很需要效率.你可能會因為使用運算符 += 代替.
The extra work is probably not worth it, unless you really really need efficiency. You probably will have much better efficiency simply by using operator += instead.
現在在免責聲明之后,我將回答您的實際問題......
Now after that disclaimer, I will answer your actual question...
STL 字符串類的效率取決于您使用的 STL 實現.
The efficiency of the STL string class depends on the implementation of STL you are using.
您可以保證效率并更好地控制自己通過c內置函數手動進行連接.
You could guarantee efficiency and have greater control yourself by doing concatenation manually via c built-in functions.
為什么 operator+ 效率不高:
看看這個界面:
template <class charT, class traits, class Alloc>
basic_string<charT, traits, Alloc>
operator+(const basic_string<charT, traits, Alloc>& s1,
const basic_string<charT, traits, Alloc>& s2)
可以看到在每個+之后返回了一個新對象.這意味著每次都使用一個新的緩沖區.如果您正在執行大量額外的 + 操作,則效率不高.
You can see that a new object is returned after each +. That means that a new buffer is used each time. If you are doing a ton of extra + operations it is not efficient.
為什么可以提高效率:
- 您是在保證效率,而不是相信代理人會為您高效地完成工作
- std::string 類對字符串的最大大小一無所知,也不知道連接它的頻率.您可能擁有這些知識,并且可以根據這些信息做事.這將導致更少的重新分配.
- 您將手動控制緩沖區,以便確保在您不希望發生這種情況時不會將整個字符串復制到新緩沖區中.
- 您可以將堆棧用于緩沖??區而不是堆,這樣效率更高.
- string + 運算符將創建一個新的字符串對象并使用新的緩沖區返回它.
實施注意事項:
- 跟蹤字符串長度.
- 保留一個指向字符串結尾和開頭的指針,或者只是開頭并使用開頭 + 長度作為偏移量來查找字符串的結尾.
- 確保您存儲字符串的緩沖區足夠大,這樣您就不需要重新分配數據
- 使用 strcpy 而不是 strcat,因此您無需遍歷字符串的長度即可找到字符串的結尾.
繩索數據結構:
如果您需要非常快速的連接,請考慮使用 繩索數據結構.
If you need really fast concatenations consider using a rope data structure.
這篇關于C++ 中的高效字符串連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!