查看 java 对象内存占用

2022/2/12 7:16:40

本文主要是介绍查看 java 对象内存占用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、直接上手

  • maven 依赖

    <dependency>
    	<groupId>org.openjdk.jol</groupId>
    	<artifactId>jol-core</artifactId>
    	<version>0.9</version>
    </dependency>
    
  • 函数使用

    import org.openjdk.jol.info.ClassLayout;
    
    public class LayoutDemo {
    	public static void main(String[] args) {
        	MyTest myTest = new MyTest();
        	System.out.println("myTest:"+myTest);
        	System.out.println(ClassLayout.parseInstance(myTest).toPrintable());
    	}
    }
    
  • 输出内容

    myTest:MyTest(a=0, b=false)
    # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
    com.pilaf.classlayout.MyTest object internals:
    OFFSET  SIZE      TYPE DESCRIPTION                               VALUE
      0     4           (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4           (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4           (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4       int MyTest.a                                  0
     16     1   boolean MyTest.b                                  false
     17     7           (loss due to the next object alignment)
    Instance size: 24 bytes
    Space losses: 0 bytes internal + 7 bytes external = 7 bytes total
    

二、详细分析

https://blog.csdn.net/weixin_40865973/article/details/105390202



这篇关于查看 java 对象内存占用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程