Is there a memory-efficient replacement of java.lang.String?

后端 未结 15 621
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 19:29

After reading this old article measuring the memory consumption of several object types, I was amazed to see how much memory Strings use in Java:



        
相关标签:
15条回答
  • 2020-11-30 20:32

    I think you should be very cautious about basing any ideas and/or assumptions off of a javaworld.com article from 2002. There have been many, many changes to the compiler and JVM in the six years since then. At the very least, test your hypothesis and solution against a modern JVM first to make sure that the solution is even worth the effort.

    0 讨论(0)
  • 2020-11-30 20:33

    There is the overhead of creating an object (at least a dispatch table), the overhead of the fact that it uses 2 bytes per letter, and the overhead of a few extra variables in there that are created to actually improve speed and memory usage in many cases.

    If you are going to use OO programming, this is the cost of having clear, usable, maintainable code.

    For an answer besides the obvious (which is that if memory usage is that important, you should probably be using C), you could implement your own Strings with an internal representation in BCD byte-arrays.

    That actually sounds fun, I might do it just for kicks :)

    A Java array takes 2 bytes per item. A BCD encoded digit takes 6 bits per letter IIRC, making your strings significantly smaller. There would be a little conversion cost in time, but not too bad really. The really big problem is that you'd have to convert to string to do anything with it.

    You still have the overhead of an object instance to worry about... but that would be better addressed by revamping your design than trying to eliminate instances.

    Finally a note. I'm completely against deploying anything like this unless you have 3 things:

    • An implementation done the most readable way
    • Test results and requirements showing how that implementation doesn't meet requirements
    • Test results on how the "improved" implementation DOES meet requirements.

    Without all three of those, I'd kick any optimized solution a developer presented to me.

    0 讨论(0)
  • 2020-11-30 20:33

    Out of curiosity, is the few bytes saved really worth it?

    Normally, I suggest ditching strings for performance reasons, in favor of StringBuffer (Remember, Strings are immutable).

    Are you seriously exhausting your heap from string references?

    0 讨论(0)
提交回复
热议问题