UPDATE
I tried the answer of
In Java, what is the best way to determine the size of an object?
but when I tried the code below, it gave me 16 for below code
public class MemoryTest {
public static void main(String[] args) {
System.out.println(ObjectSizeFetcher.getObjectSize(new ArrayList<>().add(new DummyObject())));
}
}
and 16 is not what I am looking for, so I asked this question again. Is this question still duplicated question?
I want to check the memory usage of an object, and here is what I tried. (java 8)
// Dummy Object class
public class DummyObject {
int dummy;
}
// Separate class to check memory
public class MemoryTest {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long before = runtime.totalMemory() - runtime.freeMemory();
DummyObject obj = new DummyObject();
long after = runtime.totalMemory() - runtime.freeMemory();
System.out.println(after - before);
}
}
and result is "0"
Can anyone tell me
1. why result is 0
2. what is the proper way of measuring memory usage of an object
thanks in advance
UPDATE
When I tried the same code in Android project as below, (SDK version 23)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Runtime runtime = Runtime.getRuntime();
long before = runtime.totalMemory() - runtime.freeMemory();
DummyObject obj = new DummyObject();
long after = runtime.totalMemory() - runtime.freeMemory();
System.out.println("test memory: " + (after - before));
}
}
the result was "680"
What makes this difference and why?