0

What is the impact of creating new instances of Sets, Maps and List on memory while the apex code is running. Suppose if the collection is empty the does it take a strain on the memory?How is this compared to a new instance of a custom object?

I have a requirement where I need a map whose key is an account ID and value is a Set of IDs of related objects. Later I need to access the value(the Set of IDs of related records) and then check if some IDs are present( .contains ). So even when I do not have any ID to be added the Set corresponding to an Account ID, I instantiate a new Set of ID. So I wanted to know if this is bad for performance or is it okay because in the end I am creating a new pointer to an area in the stack( which is empty). This happens in a trigger so there is a possibility of 200 such empty Sets existing.

Thanks in advance

1 Answer 1

0

Creating empty collections don't eat significant memory. It takes around 4-6 byte of your heap. So if you create 200 instances of Set of type Id then you would be using 1200 byte of memory.

Adding each Id in any set will add 18 bytes more to the heap.

Set<id> setEmpty = new Set<String>(); // 4 bytes
Set<id> setNotEmpty = new Set<String>(); // 4 bytes
setNotEmpty.add('001456789012345zWA'); // 18 bytes

In terms of performance it is not going to be a problem. But assigning such no. of Set is not a good code design practice. you should think about other ways to reduce such big number.

1
  • Thanks Ashwani. It was really informative and I agree with you.
    – Prajith
    Dec 12, 2015 at 11:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .