1

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:

  1. 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
    };
    
  2. 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?

4

1 回答 1

1

为了解决这个问题,我将重构应用程序以使用小对象。没有人真的需要在内存中过大的对象,人们通过以下方式解决这个问题:

  • 加载刚刚需要的数据(及时概念)
  • 在服务器上执行分析并返回结果
  • 使用分页或获取下一个项目
  • 使用流

现在关于您的具体问题:

从原始对象创建一个更苗条的对象会减少使用的内存吗?

不,因为无论如何您都会将这两个对象存储在内存中,实际上您只需通过创建第二个引用来稍微增加一点。您可能会加快应用程序的速度,但精心编写的软件几乎可以同等地处理大小对象(通过在非 UI 线程中运行工作)。

在两个包装对象中存储对同一对象的引用时,.NET 的行为如何?

在您的情况下,.NET 仅存储引用,简而言之,这些引用只是数字 - 指向对象本身的指针(尽管存在一些差异)。因此,当您更改单个对象时,所有引用者都会看到此更改,因为它们只是指向该对象。

加分项:不要使用公共字段,那很糟糕(单独搜索原因)

于 2013-08-02T10:59:11.580 回答