Java - used memory is greater for fewer objects

If I create 100,000 objects the used memory is greater than the used memory for 10,000,000 objects.


public class A {

    private static final int size = 1000*100;

    public static void main(String[] args) {
        double a = getMemoryInKilo();
        double start = getTime();
        for ( int i = 0 ; i < size ; i++ ) { 
            new B();
        double stop = getTime();
        double b = getMemoryInKilo();
        System.out.println(b-a + " KB ---> " + (stop-start)/1000+" seconds");

    private static double getTime(){
        return System.currentTimeMillis();

    private static double getMemoryInKilo() {
        return (double)(Runtime.getRuntime().totalMemory()- Runtime.getRuntime().freeMemory())/1000;


public class B {

    private final double k = 0;
    private final int a = 1;
    private final String s = "123456789";
    private final Object o = new Object();
    private final Integer i = 10;



  • size = 1000*100:

    4135.576 KB ---> 0.016 seconds

  • size = 1000*100*100:

    2456.064 KB ---> 0.686 seconds

I run the program with those values many times and I changed the order, but the result is the same. Used memory for 100,000 objects is bigger than used memory for 10,000,000 objects.


  • Java 1.7
  • O.S.: Windows 7
  • IDE: Eclipse Kepler


When all you do is

new B();

to allocate memory, the runtime is free to recover the allocated space whenever it wants. What you're seeing is just a coincidental difference between garbage collection activity patterns.

Each "B" object you create is immediately a candidate for garbage collection.

Need Your Help

How do I add a scalar value to a yt array?

python data-analysis yt-project

I'm trying to add a numerical floor to one of my derived fields in yt. However, when I try:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.