字符串拼接【性能对比以及优缺点】

字符串拼接性能调优:最重要的就是内存的申请

  1. StringBuilder 不知道长度最快 不安全,指针不在乎安全
  2. += 耗内存
  3. $
  4. String.Formt
  5. String.Concat 知道长度时做快

速度第一:String.Concat
速度第二:StringBuilder
速度第三:$ String.Formt 差不多并列
速度第四:+= 最耗内存 不建议使用

StringBuilder 使用方法

StringBuilder strB = new StringBuilder();

1append(String str)/append(Char c):字符串连接
System.out.println("StringBuilder:"+strB.append("hello").append("world"));
//return "StringBuilder:helloworld"

2toString():返回一个与构建起或缓冲器内容相同的字符串
System.out.println("String:"+strB.toString());
//return "String:helloworld"

3appendcodePoint(int cp):追加一个代码点,并将其转换为一个或两个代码单元并返回this
System.out.println("StringBuilder.appendCodePoint:"+strB.appendCodePoint(2));
//return "StringBuilder.appendCodePoint:helloworld "

4setCharAt(int i, char c):将第 i 个代码单元设置为 c(可以理解为替换)
strB.setCharAt(2, 'd');
System.out.println("StringBuilder.setCharAt:" + strB);
//return "StringBuilder.setCharAt:hedloworld"

5insert(int offset, String str)/insert(int offset, Char c):在指定位置之前插入字符()
System.out.println("StringBuilder.insertChar:"+ strB.insert(2, 'A'));
//return "StringBuilder.insertChar:heAlloworld"

6delete(int startIndex,int endIndex):删除起始位置(含)到结尾位置(不含)之间的字符串
System.out.println("StringBuilder.delete:"+ strB.delete(2, 4));
//return "StringBuilder.delete:heloorld"

+=使用方法

stirng  str ="a";
str= "a"+"b";

$使用方法

String str="hello";
 String str2="world";
 var ccb = $"Hi!  {str}{str2}";  

String.Format使用方法

string str= String.Format("{0}{1}","hello","world");//str="helloworld";

string.Concat使用方法

string str=string.Concat("hello","world"); //str="helloworld";

猜你喜欢

转载自blog.csdn.net/u014249305/article/details/108462710
今日推荐