AI大模型面试题:大模型训练优化全解析——AdamW、Warmup、Annealing、Scaling Law、SFT、RLHF、拒绝采样、PPO 一文讲透
2026/5/15 22:36:25
可以把字符串常量池理解成一个「字符串缓存池」:
String s = "hello")时,JVM 会先去常量池里找有没有内容为"hello"的字符串。"hello",再返回引用。new String("hello")创建的字符串,会在堆内存新建对象,同时常量池里也会创建"hello"(如果之前没有),这也是为什么new String会比直接赋值多占用内存。java
运行
public class StringConstantPoolDemo { public static void main(String[] args) { // 方式1:直接赋值,字符串存入常量池,复用已有对象 String s1 = "hello"; String s2 = "hello"; // 方式2:new 创建,堆内存新建对象,常量池仍会存"hello"(若不存在) String s3 = new String("hello"); String s4 = new String("hello"); // 对比引用(== 比较对象地址,equals 比较内容) System.out.println(s1 == s2); // true:s1和s2指向常量池同一个"hello" System.out.println(s1 == s3); // false:s1指向常量池,s3指向堆内存对象 System.out.println(s3 == s4); // false:s3和s4是堆里两个不同对象 System.out.println(s1.equals(s3)); // true:内容相同 // intern() 方法:将堆中的字符串对象"入池",返回常量池引用 String s5 = s3.intern(); System.out.println(s1 == s5); // true:s5现在指向常量池的"hello" } }存储位置:
核心方法:intern ()
intern()可优化内存。字符串拼接的特殊情况:
java
运行
String s1 = "a" + "b"; // 编译期优化,直接等同于"ab",存入常量池 String s2 = "ab"; System.out.println(s1 == s2); // true String a = "a"; String b = "b"; String s3 = a + b; // 运行期拼接,会new String("ab"),存在堆中 System.out.println(s3 == s2); // false System.out.println(s3.intern() == s2); // true==比equals更快(但仅适用于常量池字符串)。new String()会在堆创建新对象,可通过intern()方法将内容入池复用;