首页 > Windows开发 > 详细

Replicate String in C#

时间:2016-01-26 10:31:46      阅读:233      评论:0      收藏:0      [点我收藏+]

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:

Replicating Chars

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.

Replicating Strings

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()

Comparison

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.

Replicate String in C#

原文:http://www.cnblogs.com/lonelyxmas/p/5159296.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!