As can be seen here, one of String.Join's overloads works with raw pointers and uses something called UnSafeCharBuffer. Why is this? Is it a performance optimization?
1 Answer
Is a performance optimization?
Yes.
In general you should expect that unsafe code is either for low-level unmanaged language interop or for performance optimization. In this case it is the latter.
This then suggests the question:
Why not use the same techniques for StringBuilder?
Different scenarios can be tuned using different optimization techniques; StringBuilders are optimized for their scenarios.
The scenarios are different in several ways. Join knows ahead of time exactly how many bytes will be returned; StringBuilder does not. Join knows that the resulting string will be generated exactly once, but a StringBuilder has to support the create, append, ToString, append, ToString, ... workflow efficiently. And so on.
4 Comments
String.Join that actually use StringBuilder... You're only talking about a specific one.
stringis very heavily optimized.StringBuilderstill has to copy to a string as the final step. Writing directly to the return string skips that overhead.StringBuilderhas a default size that may not be entirely consumed, and continues to increase by that buffer every time you exceed. So three or four smaller strings being created is still a lot faster.StringBuilderwith an exact initial (and maximum) capacity.string. SoStringBuilderwill consume a percentage of memory defined, just to consume more memory when it becomes astring. Boils down to this yoda.arachsys.com/csharp/stringbuilder.html