6

This is an academic exercise for self study purpose to understand how things work behind scenes.

Below is the code snippet

account a;
System.debug('Current Heap:::' + Limits.getHeapSize());
a = new account(name ='Account1');
System.debug('Current Heap:::' + Limits.getHeapSize());
system.debug(a);
a = new account(name = 'Account2');
System.debug('Current Heap:::' + Limits.getHeapSize());
system.debug(a);

step2->heap size is 1070 and i point a to the object whose name is Account1,heap size increases to 1090 in following step i repoint a to another object whose name is Account2,and i expect to see an increase in Heap size.But it doesnt it remains 1090 Any idea why?

6

welcome to the forum.

When you point the variable a at the second instance of the Account, the first instance is lost to memory so the heap usage remains the same. Try it using a second variable or a list :)

List<Account> accounts = new List<Account>();
for (integer x=0; x< 10; x++) {
    System.debug('Current Heap:::' + Limits.getHeapSize());
    accounts.add(new account(name ='Account ' + x));
}
  • What do you mean by lost to memory?i thought it is there for garbage collection.But doesn't erase from memory? – sfdc99999 Jun 25 '13 at 12:42
  • 2
    Heap is the amount of memory being referenced by your running code. When you assign a to the second account, it is no longer referenced in your context and so it doesn't count to your memory usage. If you instead used b = account(name = 'Account2'); then you would see heap size increase because you are keeping reference to both. – Doug B Jun 25 '13 at 12:45
  • oh okeis. now i understand.so can we say 'garbage'[unreferenced ] values never add to your heap size? because i thought ,it does. – sfdc99999 Jun 25 '13 at 12:48
  • 2
    yes, and thinks such as garbage collection etc. are provided by the platform and not something you have to worry about or control. – Doug B Jun 25 '13 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.