如何优化 Java 中的字符串创建
可以优化 String 创建,以减少内存消耗并提高性能。使用 Java 中的 String.intern() 方法可确保相同的字符串值共享相同的内存引用。它避免为同一值创建多个对象。
优化字符串创建
声明字符串时,JVM 字符串池中会存储单个副本。如果字符串被驻留,Java 会检查池中是否有完全匹配。如果找到该字符串,它会重用现有引用;如果没有,它会将字符串添加到池中。此 string.intern() 方法 在使用多个具有相同值的字符串时也能节省内存,因为只有一个副本存储在内存中。
语法
以下是 Java String intern() 方法的语法 −
public String intern()
用于优化字符串创建的 Java 程序
以下示例使用 String.intern() 方法优化字符串创建。
public class StringOptimization {
public static void main(String[] args) {
String variables[] = new String[50000];
for( int i = 0; i < 50000; i++) {
variables[i] = "s"+i;
}
long startTime0 = System.currentTimeMillis();
for(int i = 0; i < 50000; i++) {
variables[i] = "hello";
}
long endTime0 = System.currentTimeMillis();
System.out.println("Creation time"
+ " of String literals : "+ (endTime0 - startTime0)
+ " ms" );
long startTime1 = System.currentTimeMillis();
for(int i = 0; i < 50000; i++) {
variables[i] = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with 'new' key word : "
+ (endTime1 - startTime1)
+ " ms");
long startTime2 = System.currentTimeMillis();
for(int i = 0; i < 50000; i++) {
variables[i] = new String("hello");
variables[i] = variables[i].intern();
}
long endTime2 = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with intern(): "
+ (endTime2 - startTime2)
+ " ms");
}
}
输出
Creation time of String literals : 0 ms Creation time of String objects with 'new' key word : 31 ms Creation time of String objects with intern(): 16 ms
java_strings.html

