Empalme de cadenas [comparación de rendimiento y ventajas y desventajas]

Ajuste del rendimiento del empalme de cadenas: lo más importante es la aplicación de memoria

  1. StringBuilder no conoce la longitud, la más rápida e insegura, y el puntero no se preocupa por la seguridad
  2. += consume memoria
  3. ps
  4. String.Formt
  5. String.Concat es más rápido cuando se conoce la longitud

Velocidad n.° 1: String.Concat
Velocidad n.° 2: StringBuilder
Velocidad n.° 3: $String.Formt está casi empatado con
la velocidad n.° 4: += consume más memoria y no se recomienda

Cómo usar 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"

+=Cómo usar

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

$ Cómo usar

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

Cómo usar String.Format

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

Cómo usar string.Concat

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

Supongo que te gusta

Origin blog.csdn.net/u014249305/article/details/108462710
Recomendado
Clasificación