Does a `null` object has same memory footprint as ...
# random
a
Does a
null
object has same memory footprint as a
non-null
object?
Copy code
var obj1: MyClass? = null
var obj2: MyClass = MyClass()
If we assume that with the members and methods
MyClass
is of 100 bytes. Will
obj1
also be of 100 bytes? Is there a recommended resource where I can learn more about this?
If
obj1
is just a reference and points to
null
, holds no memory. Does this mean it’s true for member variables of
MyClass
as well i.e. the members that are currently
null
?
By no memory I mean the size of the reference which shall be 4 or 8 bytes depending on the system.
p
In the first case, you don't construct the object so allocation doesn't happen. You wrote "null object" - it contradicts itself. It's just a nullable reference, set to null
👍 1
a
Can same be said for the member variables of
MyClass
if they are set to
null
? e.g.
MyClass(myOtherClass = null)
p
generally yes -
myOtherClass
just doesn't point at any object
do you have an example case that says otherwise? or just asking out of curiosity?
👍 1
a
Asking out of curiosity so I can engineer a little better. I am in the process of modelling a data class for different kind of listings. Initially I made 2 different models to keep the memory footprint low.
ListingModel
and a
DetailModel
.
ListingModel
is like a lite version of
DetailModel
. With this new information what I can do is to make
Detail
a member of
ListingModel
which is initially set to null. With this I will be able to share initial data that is already present and rest can be loaded later when a user navigates to Detail.
k
My issue with objects where you intentionally leave a property null is usability. It becomes very difficult for consumers to know what is populated in a given scenario.
k
Why not make
DetailModel
a subclass of
ListingModel
? Or make them both implement a
Model
interface?
👍 1