I'm not behind a method / operator sizeof
because I already understand that JAVA does not have this, but I need some way to measure at least on average how much an object spends from memory, even if it's using some kind of debug.
I'm not behind a method / operator sizeof
because I already understand that JAVA does not have this, but I need some way to measure at least on average how much an object spends from memory, even if it's using some kind of debug.
If your object is Serializable
, you can use java.io.ObjectOutputStream
associated with java.io.ByteArrayOutputStream
to measure the size of your object when it is serialized:
class Tamanho {
public static int tamanho(Serializable obj) {
try (
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos)
) {
oos.writeObject(obj);
oos.flush();
return baos.toByteArray().length;
} catch (java.io.IOException ex) {
// ignore a IOException que é levantada quando se fecha o oos
}
}
Here I am using the "try-with-resources" construction of Java 7, which closes the streams for me. If you are using Java 6 or earlier, you have to transform this construction into a common try
fault, but since Java 7 is already very old, here's the answer ...
If you use eclipse, this plugin might be useful link . It gives you a complete report and even lets you find out if some memory leak is occurring at some point in your application.