Memory usage of java objects

Source: Internet
Author: User

Memory usage of java objects

Case 1:

User

public class User {}

UserSizeTest

Public class UserSizeTest {static final Runtime runTime = Runtime. getRuntime (); public static void main (String [] args) {final int count = 100000; User [] us = new User [count]; long heap1 = 0; for (int I =-1; I <count; ++ I) {User user = null; user = new User (); if (I> = 0) us [I] = user; else {user = null; heap1 = getUsedMemory () ;}} long heap2 = getUsedMemory (); System. out. println ("user size:" + (float) heap2-heap1)/count + "bytes"); for (int I = 0; I <count; I ++) {us [I] = null;} runTime. gc ();} static long getUsedMemory () {return runTime. totalMemory ()-runTime. freeMemory ();}}

Result:

User size: 7.62576 bytes


Note:

An empty object occupies 8 bytes.




Case 2:

public class User {boolean flag;long id;Date date ;}

Run the test results;

User size: 23.50192 bytes

Note:

Boolean 1 + long 8 + reference type Date 4 = 13 multiple of 8 = 16
16 + null objects 8 = 24


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.