❔ Is it a problem to be creating lots of empty lists etc just to avoid null checks?
Over thousands of items, is this expensive or a problem? What is a better way to avoid null checks?
7 Replies
thousandsI don't think this is inherently a problem, but if you're creating thousands of empty lists then... maybe? Really it depends on your application. If performance is absolutely critical them you definitely shouldn't be doing this. I think you should consider if these needs to be specifically lists, because these properties have setters which implies that they're intended to be set. Why can't they just be readonly and always have the initial list as their value?
just checked whats happening in the actual program yes it could be readonly, but the data comes from database and sometimes data may not be available for each list etc so they legitimately could be null
performance isnt particularly critical i just felt like i was doing something wrong generating thousands of empty lists just to save me from null checking and wondered if there was a better way
Are you creating empty lists just to discard them later?
if there was no data available yes just creating empty lists. i guess garbage collector discards them later
It sounds like Enumerable.Empty<T>() or Array.Empty<T>() might be a better way, reading through here it sounds a more efficient equivilent https://stackoverflow.com/questions/8555865/is-there-an-empty-list-singleton-in-c
Stack Overflow
Is there an "Empty List" singleton in C#?
In C# I use LINQ and IEnumerable a good bit. And all is well-and-good (or at least mostly so).
However, in many cases I find myself that I need an empty IEnumerable<X> as a default. That is, I
It smells a bit tbh, at least in my book; you create a list on object creation just to reassign it with another list. This sounds like the object you're creating is overloaded with responsibility tbh.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.