My original posting on string repetition caused a couple responses, and is currently among the Top Posts, which indicates to me that this seems to be a frequent and non-trivial problem.
The .Net API requires that we need to handle two different cases:
If you need to replicate a character value, reader Chris points out correctly that the string constructor
s = new string(’*‘, count);
is to be used.
I found the code used in the original posting to replicate an array and convert it to a string afterwards somewhere on the web. What I did not like abound that one-liner was that it allocated first the array, and then the string, resulting in double the memory which should be necessary.
Reader StewartFip posted the StringBuilder.Insert method as a solution, which seems to do the job:
new StringBuilder().Insert(0,”myString”,count).ToString()
My guess was that allocating enough memory in the StringBuilder constructor should speed up the Insert(). Actually, it was NOT!
A small benchmarking application showed consistently, that the fastest way is to use StringBuilder.Insert(), a couple percent faster than new StringBuilder(totalsize).Insert(), and the array-to-string conversion taking twice as long.
原文:http://www.cnblogs.com/lonelyxmas/p/5159296.html