good idea to call :

 "".intern();

in a enterprise app at start up (once, like in the first servlet initialization?) so all subsequent Strings that have empty string value are the same reference?

and taking it further will there be significant gains to call intern on 50-80 strings that we know will be used a lot in this app (loaded from data base or resource file - just few strings we know can be customized but once customized for a install, rarely change) ?

有帮助吗?

解决方案

Interning the empty string (or any other string for that matter) does not give you any guarantee that subsequent instance will use the same object unless you intern them too.

The contract is that 2 Strings reference the same object (and thus are ==) if they are equals() and have both been interned.

Besides interning has a cost, each intern() implies a search in the pool.

其他提示

No seems not a good idea. It doesn't work like this. See Is it good practice to use java.lang.String.intern()?

especially @GlenBest comments on this answer: https://stackoverflow.com/a/1091081/520567

In short you gain nothing because constant strings in your source code are interned anyways and you need to intern any dynamic string during your program execution that you want interned for whatever reason.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top