2

As discussed in many questions like here and here it is recognized as a bad practice to return null values instead of empty collections.

I agree that the null returns litter the code with thousands of if (a!= null) but I wanted to know how this can impact on the memory usage when thousands of calls are done just to return an empty collection or array. Is this to be considered when an application requires memory optimization? Or the garbage collection (e.g. java) takes care of it?

Community
  • 1
  • 1
Demplo
  • 511
  • 6
  • 18
  • 1
    In most (all?) cases, `null` is a word of zeros. An empty collection will likely be two words, one a pointer to the collection, the second being a place-holder saying, "I am empty." Will using two words instead of one cause a problem? That depends on the system you are running on. Smart cards can have very limited memory. – rossum Sep 07 '14 at 16:18

1 Answers1

2

Return a static, immutable empty list instead of a new object. That way, all empty lists refer to the same static object. For example:

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Brad Schoening
  • 1,281
  • 6
  • 22