IT story

Java에서 객체의 크기 계산

hot-time 2020. 6. 16. 08:02
반응형

Java에서 객체의 크기 계산


이 질문에는 이미 답변이 있습니다.

객체가 프로젝트에 차지하는 메모리 양 (바이트 단위)을 기록하고 싶습니다 (데이터 구조의 크기를 비교하고 있습니다) .Java 에서이 작업을 수행 할 수있는 방법이없는 것 같습니다. 아마도 C / C ++에는 sizeOf()메소드가 있지만 Java에는 존재하지 않습니다. Runtime.getRuntime().freeMemory()객체를 생성하기 전후에 JVM에서 사용 가능한 메모리 를 기록한 다음 차이를 기록 하려고 시도 했지만 구조의 요소 수에 관계없이 0 또는 131304 만 제공하고 그 사이에는 아무것도 제공하지 않았습니다. 도와주세요!


java.lang.instrumentation패키지 를 사용할 수 있습니다 :

http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html

객체와 관련된 오버 헤드뿐만 아니라 구현에 대한 객체 크기의 근사치를 얻는 데 사용할 수있는 메소드가 있습니다.

Sergey가 링크 한 답변에는 훌륭한 예가 있습니다.이 글을 다시 게시 할 것입니다. 그러나 그의 의견에서 이미 보았을 것입니다.

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

getObjectSize를 사용하십시오.

public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}

출처:

Java에서 객체의 크기를 결정하는 가장 좋은 방법은 무엇입니까?


https://github.com/DimitrisAndreou/memory-measurer를 살펴보십시오. 구아바는이를 내부적으로 사용하며, ObjectGraphMeasurer는 특별한 명령 줄 인수없이 즉시 사용하는 것이 특히 간단합니다. 

import objectexplorer.ObjectGraphMeasurer;

public class Measurer {

  public static void main(String[] args) {
    Set<Integer> hashset = new HashSet<Integer>();
    Random random = new Random();
    int n = 10000;
    for (int i = 1; i <= n; i++) {
      hashset.add(random.nextInt());
    }
    System.out.println(ObjectGraphMeasurer.measure(hashset));
  }
}

java.lang.instrument.Instrumentation클래스는 Java 객체의 크기를 얻는 좋은 방법을 제공하지만 premainJava 에이전트를 사용하여 프로그램 을 정의 하고 실행해야합니다. 에이전트가 필요하지 않은 경우 매우 지루하며 애플리케이션에 더미 Jar 에이전트를 제공해야합니다.

그래서에서 Unsafe클래스를 사용하는 대체 솔루션을 얻었 습니다 sun.misc. 따라서 프로세서 아키텍처에 따라 객체 힙 정렬을 고려하고 최대 필드 오프셋을 계산하면 Java 객체의 크기를 측정 할 수 있습니다. 아래 예제에서 보조 클래스 UtilUnsafe사용 하여 sun.misc.Unsafe객체에 대한 참조를 얻습니다 .

private static final int NR_BITS = Integer.valueOf(System.getProperty("sun.arch.data.model"));
private static final int BYTE = 8;
private static final int WORD = NR_BITS/BYTE;
private static final int MIN_SIZE = 16; 

public static int sizeOf(Class src){
    //
    // Get the instance fields of src class
    // 
    List<Field> instanceFields = new LinkedList<Field>();
    do{
        if(src == Object.class) return MIN_SIZE;
        for (Field f : src.getDeclaredFields()) {
            if((f.getModifiers() & Modifier.STATIC) == 0){
                instanceFields.add(f);
            }
        }
        src = src.getSuperclass();
    }while(instanceFields.isEmpty());
    //
    // Get the field with the maximum offset
    //  
    long maxOffset = 0;
    for (Field f : instanceFields) {
        long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f);
        if(offset > maxOffset) maxOffset = offset; 
    }
    return  (((int)maxOffset/WORD) + 1)*WORD; 
}
class UtilUnsafe {
    public static final sun.misc.Unsafe UNSAFE;

    static {
        Object theUnsafe = null;
        Exception exception = null;
        try {
            Class<?> uc = Class.forName("sun.misc.Unsafe");
            Field f = uc.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            theUnsafe = f.get(uc);
        } catch (Exception e) { exception = e; }
        UNSAFE = (sun.misc.Unsafe) theUnsafe;
        if (UNSAFE == null) throw new Error("Could not obtain access to sun.misc.Unsafe", exception);
    }
    private UtilUnsafe() { }
}

"Java sizeof"에 대한 Google 검색 으로 javaworld에서 Java sizeof대한 멋진 기사가 작성되었습니다. 실제로 흥미로운 내용입니다.

To answer your question, there's not a Java equivalent of "sizeof()", but the article describes a couple of ways you can go about getting the byte size of your instantiated classes.

참고URL : https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java

반응형