话不多说,直接上代码:
/*
* Created by AaronLee on 2020 12 14
*/
package com.aaronlee.test_StringBuilder;
import org.junit.Test;
public class Test_StringBuilder {
public static void main(String[] args) {
/*
* 这里测试String与StringBuilder字符串连接效率;
* */
//String 十万级测试
String s = "abcdefghijklmnopqrstyvwxyz";
String news = "";//字符串是不能被修改的,拼接时每次都会创建对象
long start1 = System.currentTimeMillis();
for(int i = 0;i < 10_0000;i++)
{
news += s;
}
long end1 = System.currentTimeMillis();
System.out.println(end1 - start1);//260320
//StringBuilder 千万级测试;
StringBuilder sb = new StringBuilder();
long start2 = System.currentTimeMillis();
for(int i = 0;i < 1000_0000;i++)
{
sb.append(s);
}
long end2 = System.currentTimeMillis();
System.out.println(end2 - start2);//877
}
}
结果可见。10w级别测试中,用String连接需要约260秒。而StringBuilder进行千万级测试只需要不到一秒;
方法测试:
/*
* append(boolean/char/char[]/CharSequence/double/float/int/long/Object/String/StringBuffer)
* 讲某某参数的字符串表示附加到序列中;
* 返回值“StringBuilder
*/
@Test
public void Test_append()
{
StringBuilder sb = new StringBuilder();
sb.append(true);
sb.append('哈');
char[] ch = {'A','B','V'};
sb.append(ch);
sb.append("服了");
sb.append(123.1d);
sb.append(1.23f);
sb.append(123);
sb.append(1892671876389L);
Object o = new Object();
sb.append(o);
sb.append("按时");
StringBuffer sb1 = new StringBuffer("jsaughagjhgdsjhavjhvajhKg尽快改扩建不合格i");
sb.append(sb1);
System.out.println(sb);
//结果:true哈ABV服了123.11.231231892671876389java.lang.Object@14514713按时jsaughagjhgdsjhavjhvajhKg尽快改扩建不合格i
/*
* append(CharSequence s,int start,int end);
*/
sb.append("卧槽,无情!",1,4);
System.out.println(sb);//将 槽,无(index大于等于1小于4)的字符串连接到sb的末尾;
}
/**
* capacity()
* 返回当前容量
* 返回值 : int
*/
@Test
public void Test_capacity()
{
StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
System.out.println(sb.capacity());//42 ??
StringBuilder sb1 = new StringBuilder("我爱中国!");
System.out.println(sb1.capacity());//21
/*
* 虽然返回的是容量,但是不知道怎么算的;
* API解释:确保容量至少等于规定的最小值。如果当前容量小于参数,则会分配一个新的内部数组,容量更大。新产能较大;
* 涉及到minimumCapacity- 最低所需容量
*/
}
/**
* charAt(int index);
* 返回指定索引在这里的序列值;理解为返回索引位置的值
* 返回值:char
*/
@Test
public void Test_charAt()
{
StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
System.out.println(sb.charAt(10));//k
}
/**
* codePointAt(int index)
* 返回指定索引处的字符(数字) --(Unicode代码点)
* 返回值:int
*/
@Test
public void Test_codePointAt()
{
StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
System.out.println(sb.codePointAt(0));//97
}
/**
* codePointBefore(int index)
* 返回指定索引之前的数字(Unicode代码点)
* 返回值 int
*/
@Test
public void Test_codePointBefore()
{
StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
System.out.println(sb.length());//这里是 sb的长度,长度-1就是最后的索引值;
System.out.println(sb.codePointBefore(sb.length() - 1));//121
}
/**
* delete(int start, int end)
* 删除次序列的子字符串中的字符;
* 返回值 :StringBuilder
*/
@Test
public void Test_delete()
{
StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
System.out.println(sb.delete(0, 10));//klmnopqrstuvwxyz
//可见 start和end为索引值,范围左闭右开
}