String vs char[]

后端 未结 4 558
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 03:11

I have some slides from IBM named : \"From Java Code to Java Heap: Understanding the Memory Usage of Your Application\", that says, when we use String instead of <

4条回答
  •  梦谈多话
    2021-01-30 03:47

    I had read from old stackoverflow answer not able to get it. In Oracle's JDK a String has four instance-level fields:

    A character array
    An integral offset
    An integral character count
    An integral hash value
    

    That means that each String introduces an extra object reference (the String itself), and three integers in addition to the character array itself. (The offset and character count are there to allow sharing of the character array among String instances produced through the String#substring() methods, a design choice that some other Java library implementers have eschewed.) Beyond the extra storage cost, there's also one more level of access indirection, not to mention the bounds checking with which the String guards its character array.

    If you can get away with allocating and consuming just the basic character array, there's space to be saved there. It's certainly not idiomatic to do so in Java though; judicious comments would be warranted to justify the choice, preferably with mention of evidence from having profiled the difference.

提交回复
热议问题