String vs char [] [英] String vs char[]

查看:142
本文介绍了String vs char []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些来自IBM的幻灯片名为:。

  • 计算地图条目的内存 - 获取对象大小的简单方法。


  • 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 char[], there is

    Maximum overhead would be 24:1 for a single character!

    but I am not able to understand what overhead is referred here. Can anybody please help?

    Source :

    解决方案

    This figure relates to JDK 6- 32-bit.

    JDK 6

    In pre-Java-7 world strings which were implemented as a pointer to a region of a char[] array:

    // "8 (4)" reads "8 bytes for x64, 4 bytes for x32"
    
    class String{      //8 (4) house keeping + 8 (4) class pointer
        char[] buf;    //12 (8) bytes + 2 bytes per char -> 24 (16) aligned
        int offset;    //4 bytes                     -> three int
        int length;    //4 bytes                     -> fields align to
        int hash;      //4 bytes                     -> 16 (12) bytes
    }
    

    So I counted:

    36 bytes per new String("a") for JDK 6 x32  <-- the overhead from the article
    56 bytes per new String("a") for JDK 6 x64.
    


    JDK 7

    Just to compare, in JDK 7+ String is a class which holds a char[] buffer and a hash field only.

    class String{      //8 (4) + 8 (4) bytes             -> 16 (8)  aligned
        char[] buf;    //12 (8) bytes + 2 bytes per char -> 24 (16) aligned
        int hash;      //4 bytes                         -> 8  (4)  aligned
    }
    

    So it's:

    28 bytes per String for JDK 7 x32 
    48 bytes per String for JDK 7 x64.
    

    UPDATE

    For 3.75:1 ratio see @Andrey's explanation below. This proportion falls down to 1 as the length of the string grows.

    Useful links:

    这篇关于String vs char []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆