gpt4 book ai didi

c# - TextBox.Text += "string";与 TextBox.AppendText ("string");

转载 作者:太空狗 更新时间:2023-10-29 20:02:56 28 4
gpt4 key购买 nike

这两种方法有什么区别?

一个比另一个更有效率吗?

我在想 AppendText() 可能使用类似于 StringBuilder 的方法,即它使用自己的缓存而不是每次都创建和附加一个新字符串,是这样吗?

谢谢。

最佳答案

正如Remarks section of MSDN Documentation中明确提到的那样

The AppendText method enables the user to append text to the contents of a text control without using text concatenation, which, can yield better performance when many concatenations are required.

你的问题,

what is the difference between these two methods?

我们都知道 TextBox.Text += something; 是如何工作的,即每次创建和附加一个新字符串但是 AppendText 是如何工作的我找不到任何代码片段它在内部是否使用 StringBuilder 或其他东西。

Is one more efficient than the other?

我认为上述问题的答案将视情况而定,(基于测试用例观察)

if Multiline property is set to false then Concatenation (+=) yields better results but on other hand Multiline property is set to true then AppendText yields far better performance.

编辑 阅读 comment from Rawling 后我制作了一个自定义的 win-form 解决方案,其中我有一个简单的 textbox,我在其中附加了一个简单的字符串 hello 10000 次,使用一个简单的 for循环

    private void btnAppendText_Click(object sender, EventArgs e)
{
txtText.Text = string.Empty;
DateTime startTime = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
txtText.AppendText(s);
}
DateTime endTime = DateTime.Now;
txtTime.Text = (endTime.Ticks - startTime.Ticks).ToString();
}

private void btnConcante_Click(object sender, EventArgs e)
{
txtText.Text = string.Empty;
DateTime startTime = DateTime.Now;
for (int i = 0; i < 5000; i++)
{
txtText.Text += s;
}
DateTime endTime = DateTime.Now;
txtTime.Text = (endTime.Ticks - startTime.Ticks).ToString();
}

输出非常令人惊讶,
测试 1:多行属性为真我不得不将迭代次数减少到一半,即 5000 次用于文本连接,因为这需要很长时间。

btnAppendText_Click output on txtTime was 37222129 almost 3-4 seconds for 10000 iteration
btnConcante_Click output on txtTime was 14449906487 more than 25 minutes for only 5000 iterations.

从上面的结果很明显,AppendText 更快更有效(当 Multilinetrue 时) >串联

测试 2:多行属性为假

btnConcante_Click output on txtTime was 39862280 almost 3-4 seconds for 10000 iteration
btnAppendText_Click output on txtTime was 1043279672 almost 2-3 minutes for 10000 iteration

从上面的结果可以明显看出,Concatenation 比 AppendText 更快更有效(当 Multilinefalse 时)

关于c# - TextBox.Text += "string";与 TextBox.AppendText ("string");,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20632372/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com