问题描述
所以...在这种情况下,我有一个Foreach循环,该循环遍历复选框列表以检查选中了哪些复选框。对于每个选中的复选框,我必须进行一个很长的字符串连接,包括30个平均长度为20个字符的不同字符串,然后将其作为HTTP请求发送出去。其中两个字符串取决于所选复选框的索引/值。
So...I have this scenario where I have a Foreach loop that loops through a List of Checkboxes to check which are selected. For every selected checkbox, I have to do a pretty long string concatenation, involving 30 different strings of an average length of 20 characters, and then send it out as a HTTP request. 2 of the strings are dependant on the index/value of the checkbox selected.
复选框列表的长度也取决于用户的数据而变化。我要说的是,名单的平均长度为20,但最多可以达到50-60。因此,最坏的情况是将整个字符串连接执行60次左右。
The length of the List of Checkboxes is also variable depending upon the user's data. I would say the average length of the List would be 20, but it can go up to 50-60. So the worst case scenario would be performing the whole string concatenation 60 or so times.
现在,我正在通过'+'运算符使用简单的字符串连接来执行此操作,但是我想知道用Stringbuilder这样做是否会更快。当然,这意味着我要么必须在循环中创建一个Stringbuilder对象,要么在循环之前创建它并调用Stringbuilder。在发出HTTP请求后在其末尾删除它。
For now I'm doing it with simple string concatenation via the '+' operator, but I'm wondering if it would be faster to do it with Stringbuilder. Of course, that means I'd have to either create a Stringbuilder object within the loop, or create it before the loop and call Stringbuilder.Remove at the end of it after sending out the HTTP request.
我感谢任何人可以就此问题分享任何见解。
I appreciate any insights anybody can share regarding this issue.
编辑
所有人的所有答复,因此从我收集到的信息来看,对我来说最好的方法是:
EDIT
Thanks for all the replies everybody, so from what I've gathered, the best way for me to go about doing this would be something like:
StringBuilder sb = new StringBuilder();
foreach (CheckBox item in FriendCheckboxList)
{
if (item.Checked)
{
sb.Append(string1);
sb.Append(string2);
sb.Append(string3);
.
.
.
sb.Append(stringLast);
SendRequest(sb.ToString());
sb.Length = 0;
}
}
推荐答案
使用 StringBuilder
。就是这样。
字符串是不可变的。字符串串联会创建一个新的字符串,需要更多的内存,并且通常被认为很慢:
Strings are immutable. String concatenation creates a new string, needing more memory, and is generally considered slow:
string a = "John" + " " + "Saunders";
这将创建一个字符串 John,然后创建另一个字符串 John Saunders,最后,分配到一个。
This creates a string "John ", then creates another string "John Saunders", then finally, assigns that to "a". The "John " is left for garbage collection.
string a = "John";
a += " ";
a += "Saunders";
这大致相同,因为 John被新的字符串 John代替,被新的字符串 John Saunders替换。
This is about the same, as "John" is replaced by a new string "John ", which is replaced by a new string "John Saunders". The originals are left to be garbage collected.
另一方面, StringBuilder
旨在被附加,删除。 ,等等。
On the other hand, StringBuilder
is designed to be appended, removed, etc.
示例:
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++)
{
sb.Length = 0;
sb.Append(field1[i]);
sb.Append(field2[i]);
...
sb.Append(field30[i]);
// Do something with sb.ToString();
}
这篇关于字符串连接与字符串生成器追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!