本文介绍了在Java中,确定对象大小的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我有一个应用程序可以读取包含大量数据行的CSV文件。我根据数据类型向用户提供行数的摘要,但我想确保我没有读取太多数据行并导致 OutOfMemoryError 秒。每行都转换为一个对象。有没有一种简单的方法可以通过编程方式找出该对象的大小?是否有一个引用定义了 VM 的原始类型和对象引用的大小?

For example, let's say I have an application that can read in a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a VM?

现在,我有代码说读 32,000行,但我也想让代码尽可能多地读取行,直到我使用 32MB 的内存。也许这是一个不同的问题,但我仍然想知道。

Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory. Maybe that is a different question, but I'd still like to know.

推荐答案

你可以使用

编译并将此类放入JAR:

Compile and put this class in a JAR:

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);
    }
}

将以下内容添加到 MANIFEST.MF

Premain-Class: ObjectSizeFetcher

使用getObjectSize:

Use getObjectSize:

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

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

调用:

java -javaagent:ObjectSizeFetcherAgent.jar C

这篇关于在Java中,确定对象大小的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:02