C# 中的字符串连接
我的页面之一在 *.cs 文件中使用 jQuery,如下所示。但我听说字符串连接会降低性能。我无法将其写入页面(即 *.aspx),因为我正在使用 UpdatePanel,它会清除所有客户端代码。还有其他替代方法吗? StringBuilder 怎么样?
代码位于 MyTestPage.aspx.cs 中,字符串使用 + 连接
// Function to be called by jQuery
@"function ddlAssignCaseTo_SelectIndexChanged() {
var value = $('#" + ddlAssignCaseTo.ClientID + @"').val();
value == '1' ? $('#" + divAction.ClientID + @"').show() : $('#" + divAction.ClientID + @"').hide();
}
function ddlReviewedBy_SelectIndexChanged() {
var value = $('#" + ddlReviewedBy.ClientID + @"').val();
value == '0'
? $('#" + divReviewee.ClientID + @"').hide()
: $('#" + divReviewee.ClientID + @"').show();
value == '0'
? $('#" + lblIn.ClientID + @"').hide()
: $('#" + lblIn.ClientID + @"').show();
}"
One of my page uses jQuery in *.cs file as follows. But I heard that string concatenation will reduce the performance. I can not write it in page (ie in *.aspx) because I am using UpdatePanel, which wipe out all client code. Is there any other alternative method ? How about StringBuilder?
The code is in MyTestPage.aspx.cs and strings are concatenated using +
// Function to be called by jQuery
@"function ddlAssignCaseTo_SelectIndexChanged() {
var value = $('#" + ddlAssignCaseTo.ClientID + @"').val();
value == '1' ? $('#" + divAction.ClientID + @"').show() : $('#" + divAction.ClientID + @"').hide();
}
function ddlReviewedBy_SelectIndexChanged() {
var value = $('#" + ddlReviewedBy.ClientID + @"').val();
value == '0'
? $('#" + divReviewee.ClientID + @"').hide()
: $('#" + divReviewee.ClientID + @"').show();
value == '0'
? $('#" + lblIn.ClientID + @"').hide()
: $('#" + lblIn.ClientID + @"').show();
}"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是 Javascript——你是用 C# 来构建它的吗?
无论如何,如果您没有在循环或其他内容中连接字符串,那么创建 StringBuilder 的开销是不值得的。我经常引用的一条经验法则是,当您的连接次数超过 8 倍时,请更改为
StringBuilder
- 但我看到更多的基准测试表明它不止于此。请记住,无论如何,内联连接都会被优化:
不慢于:
That's Javascript - are you building that up somehow in C#?
Anyway, if you aren't concatenating the string within a loop or something then the overhead of creating a
StringBuilder
is not worth it. A rule of thumb I've seen often cited is to change to aStringBuilder
when you have more than 8x concats - but I've seen more benchmarks which suggest that it is more than this.Remember that inline concatenations will be optimised out anyway:
Is no slower than:
在这种情况下,您应该使用
String.Format("#{0}", ddlAssignCaseTo.ClientID)
,因为它在幕后使用 StringBuilder,但允许您保持代码简洁。您当然应该尝试避免连接所提供的所有答案的字符串。
In this case you should use
String.Format("#{0}", ddlAssignCaseTo.ClientID)
as this uses StringBuilder under the hood but allows you to keep your code concise.You should certainly try and avoid concatenating strings for all the answers provided.
您可能比使用 < 做得更糟糕code>StringBuilder 正是出于这个原因而设计的。
You could do worse than use
StringBuilder
which is designed for this very reason.