Java에서 개체 크기 계산
오브젝트가 프로젝트에 소비하는 메모리(바이트 단위)를 기록하려고 합니다(데이터 구조의 크기를 비교하고 있습니다). Java에서는 이 작업을 수행할 수 있는 방법이 없는 것 같습니다.아마도 C/C++는sizeOf()
method. 단, Java에서는 존재하지 않습니다.JVM에 빈 메모리를 기록하려고 했습니다.Runtime.getRuntime().freeMemory()
오브젝트를 작성하기 전후에 차이를 기록하지만 구조물의 요소 수에 관계없이 0 또는 131304만 표시되며 그 사이에는 아무것도 표시되지 않습니다.도와주세요!
패키지를 사용할 수 있습니다.
오브젝트 크기 및 오브젝트와 관련된 오버헤드의 구현별 근사치를 얻기 위해 사용할 수 있는 메서드가 있습니다.
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()));
}
}
https://github.com/DimitrisAndreou/memory-measurer 를 참조해 주세요.
Guava는 내부적으로 사용하고 있습니다.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
class는 Java 객체의 크기를 취득하는 좋은 방법을 제공하지만, 이 방법을 사용하려면premain
Java 에이전트를 사용하여 프로그램을 실행합니다.에이전트가 필요 없고 애플리케이션에 더미 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() { }
}
언급URL : https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java
'sourcecode' 카테고리의 다른 글
VueJs가 함수 내의 데이터 속성에 액세스할 수 없습니다. (0) | 2022.08.12 |
---|---|
ATOMIC Integer의 실용적 용도 (0) | 2022.08.12 |
LD_PRELOAD를 사용하여 여러 파일 지정 (0) | 2022.08.12 |
연결 Java - MySQL: 공용 키 검색이 허용되지 않습니다. (0) | 2022.08.12 |
서브디렉토리에서 Vue.js 웹팩 프로젝트를 처리하는 방법 (0) | 2022.08.12 |