关于字符串实习性能的问题
我很好奇。该场景是一个 Web 应用程序/站点,例如具有 100 个并发连接和每秒许多(20?)页面加载。
如果应用程序需要提供格式化字符串,
string.Format("Hello, {0}", username);
“Hello, {0}”是否会被保留?还是只能实习
string hello = "Hello, {0}";
string.Format(hello, username);
,就实习而言,会提供更好的表现:上述或
StringBuilder builder = new StringBuilder()
builder.Append("Hello, ");
builder.Append(username);
什至
string hello = "Hello, {0}";
StringBuilder builder = new StringBuilder()
builder.Append("Hello, ");
builder.Append(username);
所以我的主要问题是: 1) string.Format 文字是否会被保留 2)是否值得为字符串生成器设置变量名以进行快速查找,或者 3)查找本身是否相当繁重(如果上面的#1是“否”)
我意识到这可能会导致微小的收益,但正如我所说,我很好奇。
I'm curious. The scenario is a web app/site with e.g. 100's of concurrent connections and many (20?) page loads per second.
If the app needs to server a formatted string
string.Format("Hello, {0}", username);
Will the "Hello, {0}" be interned? Or would it only be interned with
string hello = "Hello, {0}";
string.Format(hello, username);
Which, with regard to interning, would give better performance: the above or,
StringBuilder builder = new StringBuilder()
builder.Append("Hello, ");
builder.Append(username);
or even
string hello = "Hello, {0}";
StringBuilder builder = new StringBuilder()
builder.Append("Hello, ");
builder.Append(username);
So my main questions are:
1) Will a string.Format literal be interned
2) Is it worth setting a variable name for a stringbuilder for a quick lookup, or
3) Is the lookup itself quite heavy (if #1 above is a no)
I realise this would probably result in minuscule gains, but as I said I am curious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有一个静态方法 String.IsInterned(str) 方法。您可以做一些测试并找出答案!
http://msdn.microsoft.com/en-us/library /system.string.isinterned.aspx
There is a static method String.IsInterned(str) method. You could do some testing and find out!
http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx
String.Format 实际上在内部使用了 StringBuilder,因此没有理由在代码中直接调用它。就文字的驻留而言,两个代码版本是相同的,因为 C# 编译器将创建一个临时变量来存储文字。
最后,在网页中实习的效果可以忽略不计。页面渲染本质上是一个繁重的字符串操作操作,因此实习造成的差异可以忽略不计。通过使用页面和控件缓存,您可以以更简单的方式获得更大的性能优势。
String.Format actually uses a StringBuilder internally, so there is no reason to call it directly in your code. As far as interning of the literal is concerned, the two code versions are the same as the C# compiler will create a temporary variable to store the literal.
Finally, the effect of interning in a web page is negligible. Page rendering is essentially a heavy-duty string manipulation operation so the difference interning makes is negligible. You can achieve much greater performance benefits in a much easier way by using page and control caching.
快速回答:运行 10 万次迭代并找出答案。
Quick answer: run a 100k iterations and find out.
你就无法击败。
如果你的场景真的那么简单,
You can't beat
if your scenario is really that simple.