Reputation: 1585
Lets say I have a class with a really large object, which lets say is a list of objects and loads of data into memory by fetching from the DB. This is for a WPF application.
public class MyClass {
public ReallyLargeObject largeObject;
//Other properties.
}
I have a view model(VM1) object which has a reference to bind this class to the XAML.
I need another view model (VM2) with only a certain properties of MyClass and not the largeObject.
Two scenarios:
I can assign VM2.myClass = VM1.myClass
var viewModel1 = new VM1() { myClass = new MyClass() { largeObject = new ReallyLargeObject(); //initialize other properties } }; var viewModel2 = new VM2() { myClass = viewModel1.myClass };
I can create a new object of type MyClass from VM1.myClass but this time setting largeObject = null
var viewModel1 = new VM1() {
myClass = new MyClass() {
largeObject = new ReallyLargeObject();
//initialize other properties
}
};
var viewModel2 = new VM2(){
myClass = new MyClass(){
//initialize other properties
}
};
Both the viewmodels will be in memory during runtime fairly for a significant amount of time.
I'm facing an issue with the first approach taking a lot of memory and the screen being rather slow.
Would creating a slimmer object from the original object reduce the memory used?
I'm confused cause the view model 2 technically has only the reference to the object in view model 1.
How does .NET behave when storing references to same object in two wrapping objects?
Is it like other languages where the reference alone would be stored and the memory allocated on the heap to the object is the same?
Upvotes: 1
Views: 271
Reputation: 35925
To solve the problem I'd refactor the application to use small objects. No one really needs excessively huge objects in memory and people get around this by:
Now regarding your specific questions:
Would creating a slimmer object from the original object reduce the memory used?
No, because you would store both objects in memory anyway, in fact you would just make a tiny increase by creating a second reference. You might speed up your application, but a carefully written software would nearly equally operate on large and small objects (by running work in the non-UI thread).
How does .NET behave when storing references to same object in two wrapping objects?
In your case .NET only stores the references, which are, in a nutshell, just numbers - pointers to the object itself (there are some differences though). So that when you change a single object, all the referrers will see this change, as they just point to the object.
Bonus points: don't use public fields, that's just bad (search for the reasons separately)
Upvotes: 1