LoginSignup
0
0

More than 3 years have passed since last update.

Java の Object のサイズを簡単に測定する

Posted at

コード

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ObjectUtils {
    public static int getObjectSize(Object o) {
        ObjectOutput out = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            out = new ObjectOutputStream(bos);
            out.writeObject(o);
            out.flush();
            byte[] b = bos.toByteArray();
            return b.length;
        } catch (IOException e) {
            return -1;
        }
    }
}

使い方

    public static void main(String[] args) {
        {
            String o = "ABC";
            System.err.println(ObjectUtils.getObjectSize(o));
        }
        {
            Integer o = 100;
            System.err.println(ObjectUtils.getObjectSize(o));
        }
        {
            String[] o = { "ABC", "ABC", "ABC" };
            System.err.println(ObjectUtils.getObjectSize(o));
        }
    }

実行結果例

10
81
60
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0