When to use intern() on String literals

前端 未结 4 1705
迷失自我
迷失自我 2020-11-30 00:22

I see a lot of legacy code like this:

class A {
    public static final String CONSTANT = \"value\".intern();
    ...
}

I don\'t see any re

4条回答
  •  时光说笑
    2020-11-30 01:11

    A while ago I intern()ed all of the Strings coming from class files (for a classfile parser). Intern()ing made the program use less memory (won't in this case as others have pointed out) but it did slow the program down significantly (I think it took 4 seconds to parse all of rt.jar and that change put it over 8 seconds). Looking into it at the time (was JDK 1.4 I think) the intern() code is pretty ugly and slower that in probably needs to be.

    If I were to consider calling intern() in my code I would first profile it without intern() and then profile it with intern() for both memory and speed and see which one is "worse" for the change.

提交回复
热议问题