|
突然要用到把一个String重复N遍不是循环的方法,结果居然没有。 CSDN上找了下,人家也说没有,方法找到很多,看到一个效率最高的。贴出来给大家评评为什么效率最高 { char[] arr = str.ToCharArray(); char[] arrDest = new char[arr.Length * n]; for (int i = 0; i < n; i++) { Buffer.BlockCopy(arr, 0, arrDest, i * arr.Length * 2, arr.Length * 2); } return new string(arrDest); } 感觉是内存分配上面效率高吧,可能~~:) 把这个方法改成泛型会不会就没效率了呢? public static string RepeatString(T str, int n) { string s = str.ToString(); char[] arr = s.ToCharArray(); char[] arrDest = new char[arr.Length * n]; for (int i = 0; i < n; i++) { Buffer.BlockCopy(arr, 0, arrDest, i * arr.Length * 2, arr.Length * 2); } return new string(arrDest); } } posted on |