Search code examples
javastringcompilationcompile-timecompile-time-constant

Do String constants/literals in code slow down compiling considerably?


String compile time constants (internalized-strings) and literals can be compared with the ==, as they are assigned the same reference at compile-time if they are equal somehow.

Does this mean that compiling code consisting of n String literals takes n log(n) time to compile?

I ask this question here because someone might already know the answer and I'm not certain I can write a test that measures the effect in a reliable, reproducable or significant way. Or that this test would reflect real world constrains etc..

I'm going to publish any test cases I can come up with though, feel free to suggest some, I will implement them as soon as I can find the time.


Solution

  • Do String constants/literals in code slow down compiling considerably?

    No.

    String compile time constants (internalized-strings) and literals can be compared with the ==, as they are assigned the same reference at compile-time if they are equal somehow.

    No they aren't. They are pooled at compile time into the constants area of the .class file, and they are interned at class-loading time, when the reference is assigned.

    Does this mean that compiling code consisting of n String literals takes n log(n) time to compile?

    No. There is no inherently O(N log(N)) process here. Pooling is O(1) via a hash table in any sensible implementation, and interning ditto.

    [It would of course be possible to construct a compiler or intern() method that was O(N log(N)), or O(N^3) or worse, but it isn't entailed by anything in your question.]