Why is string.intern() so slow?

前端 未结 4 907
萌比男神i
萌比男神i 2020-12-13 00:50

Before anyone questions the fact of using string.intern() at all, let me say that I need it in my particular application for memory and performance reasons.

4条回答
  •  情话喂你
    2020-12-13 01:19

    @Michael Borgwardt said this in a comment:

    intern() is not synchronized, at least at the Java language level.

    I think that you mean that the String.intern() method is not declared as synchronized in the sourcecode of the String class. And indeed, that is a true statement.

    However:

    • Declaring intern() as synchronized would only lock the current String instance, because it is an instance method, not a static method. So they couldn't implement string pool synchronization that way.

    • If you step back and think about it, the string pool has to perform some kind of internal synchronization. If it didn't it would be unusable in a multi-threaded application, because there is simply no practical way for all code that uses the intern() method to do external synchronization.

    So, the internal synchronization that the string pool performs could be a bottleneck in multi-threaded application that uses intern() heavily.

提交回复
热议问题