字符串常量池 - StringTable
一:配置常量池大小
-XX:StringTableSize=60013
-
JDK1.6默认为1009,JDK1.7之后默认为60013,字符串常量池底层为HashTable,合理增大常量池大小会解决Hash冲突问题
-
JDK1.8开始1009是可以设置的最小值
二:测试(常量池大小对执行效率的影响)
package xyz.xx.chapter_string;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* -XX:StringTableSize=1009 -> 141ms
* -XX:StringTableSize=100009 -> 43ms
*/
public class StringTest3 {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "UTF-8"));
long start = System.currentTimeMillis();
String data;
while ((data = br.readLine()) != null) {
data.intern();
}
long end = System.currentTimeMillis();
System.out.println("耗時: "+(end-start)+"ms");
}catch(IOException e){
e.printStackTrace();
}
}
}
package xyz.xx.chapter_string;
import java.io.*;
/**
* -XX:StringTableSize=1009
* -XX:StringTableSize=100009
*/
public class StringTest2 {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"),"UTF-8"));
for(int i=0;i<100000;i++){
int length = (int)(Math.random()*(10-1+1)+1);
bw.write(getString(length) + "\n");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getString(int length) {
String res = "";
for(int i=0;i<length;i++){
// 65-90 97-122
int num = (int)(Math.random()*(90-65+1)+65)+(int)(Math.random()*2)*32;
res += (char)num;
}
return res;
}
}
三:测试(字符串字面量的不变型)
package xyz.xx.chapter_string;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* hello
* ABCDEFG
* [?, B, C]
* [hello, world]
* 10
*/
public class StringTest1 {
public static void main(String[] args) {
String a = "ABCDEFG";
char[] chs = {'A','B','C'};
test1(a,chs);
System.out.println(a);
System.out.println(Arrays.toString(chs));
List<String> list = new LinkedList<>();
list.add("hello");
list.add("world");
test2(list);
System.out.println(list);
int number = 10;
test3(number);
System.out.println(number);
}
public static void test1(String str, char[] charArray){
str = "hello";
System.out.println(str);
charArray[0] = '?';
}
public static void test2(List<String> list){
list = new LinkedList<String>();
list.add("test2");
}
public static void test3(int a){
a = 99;
}
}