1

I need memory used by an object on run time for some analysis purpose. I am using netbeans 5.1 which doesn't support profiling and I can't use later version of netbeans due to project compatibility. Please suggest some alternative for this with detailed explanation.

Jeremy Goodell
  • 18,225
  • 5
  • 35
  • 52
Rupesh S.
  • 41
  • 7
  • 2
    Looks like a dup of http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object – gogasca Aug 04 '15 at 17:30

2 Answers2

0

This is just for an understanding of how it works:

For example if you have a class like:

public class A{
    int i;
    long l;
    double a[]=new double[N];
   }   

The memory cost will be as follows:

1) Object Overhead : 16 bytes

2) for int i : 4 bytes

3) for long l: 8 bytes

4) For array of type double a : 8*N(8 bytes for double*number of elements in the array)+24 bytes overhead+8 bytes reference to the array

5) Now you add padding bytes so that the total sum of bytes is divisible by 8.
And similar goes for other primitives also.

hermit
  • 1,048
  • 1
  • 6
  • 16
0

Solution: Convert Object to ByteArrray and get the length of the array. It should work in older java versions too.

 import java.io.*;  

    class ObjectData implements Serializable{
        private int id=1;;
        private String name="sunrise76";
        private String city = "Newyork";
        private int dimensitons[] = {20,45,789}; 
    }

    public class ObjectSize{
        public static void main(String args[]){
            try{
            ObjectData data = new ObjectData();
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(b);
            oos.writeObject(data);
            System.out.println("Size:"+b.toByteArray().length);
            }catch(Exception err){
                err.printStackTrace();
            }
        }
    }

Output from the program for "java ObjectSize"

Size:156

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211