开发者

Concatenation with StringBuilder

开发者 https://www.devze.com 2023-01-06 11:49 出处:网络
Is it from a开发者_StackOverflow社区 sight of resources reasonable to use a StringBuilder already to concat two strings or is there a minimum concatenation operations that makes the StringBuilder effi

Is it from a开发者_StackOverflow社区 sight of resources reasonable to use a StringBuilder already to concat two strings or is there a minimum concatenation operations that makes the StringBuilder efficient?


...the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated


String.Join is the fastest one as it allocates all the required memory in one operation. See this article: StringBuilder vs. String / Fast String Operations with .NET 2.0


Concatenating two strings with StringBuilder won't give you any benefits, since the result still has to be converted to a string - so concatenating them directly is one allocation + two copies. StringBuilder can't do any better - only clutter your code.


If you're asking the question, you're probably making a decision on what technique to use in order to get good performance.

If you're attempting to get good performance then you probably have a suite of carefully-designed performance tests which clearly show the differences between two different techniques, measured along a set of realistic, user-focussed performance scenarios.

If you have such a suite, why are you asking us? Just run it both ways and see which one gives you better performance!

If you don't have such a suite, you're never going to get good performance out of a slow application by asking questions random people on the internet who do not know your customers, your code, or your scenarios. Build yourself a carefully-designed suite of performance tests which allows you to measure the difference between two techniques and compare that against a realistic set of user-focused performance goals.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号