MyObject =新对象的内存使用 [英] MyObject = New Object memory use

查看:80
本文介绍了MyObject =新对象的内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能早就想过一个问题,但是无论如何:

让我说我将一个对象(例如数据集)变暗,用数据填充该对象,然后使用该对象,但不要在使用后将其明确清除/清空.然后像这样重新使用它:

A question I should have probably wondered about a little earlier, but anyway:

Let''s say I dim an object, for example a dataset, fill that object with data, and use the object, but do not explicitly clear/empty it after use. Then reuse it like:

MyObject = New Object


是否会自动清除/清空我之前填充的数据?还是这取决于对象?

也许这里的重要问题是:什么是最佳实践?我可以通过在重用对象之前未明确清除/清空对象来解决问题吗?


Will that automatically clear/empty the data from it, that I filled it with earlier? Or does this depend on the object?

Perhaps the important question here is: what is best practice? Can I get problems by not explicitly clearing/emptying an object before reusing it?

推荐答案



假设VB.NET,如果您这样做
Hi,

assuming VB.NET, if you do
<br />[1]   Dim MyObject As Object<br />[2]   MyObject = New Object  '' object 1<br />[3]   MyObject = New Object  '' object 2<br />



然后,当执行第[3]行时,对象1将变为可收集的,这意味着垃圾收集器将在下次运行对象1时对其进行收集(通常,如果不先清理内存就无法满足将来的内存分配,则垃圾收集器将运行).

这很好,除非它是实现Dispose或Close的类型,例如:



then object 1 will become collectible when line [3] executes, meaning the garbage collector will collect object 1 the next time it runs (normally it runs when a future memory allocation cannot be satisfied without cleaning up memory first).

And this is fine, unless it is a type that implements Dispose or Close, as in:

<br />[1]   Dim MyObject As Font<br />[2]   MyObject = New Font(...) '' object 1<br />[4]   MyObject = New Font(...) '' object 2<br />



现在您应该插入[3] MyObject.Dispose()以确保可能保留的非托管资源立刻释放对象(或文件或流或任何关闭的对象).

如果不关闭/处理支持该对象的对象,则您的应用将占用更多的内存和其他系统资源,并且其行为可能会恶化.是的,垃圾收集器仍会找到那些对象,并且其终结器线程最终将把它们丢弃,但这通常要晚得多.

:)



now you should insert [3] MyObject.Dispose() to make sure the unmanaged resources that might be held by the object get released right away (or the file or stream or whatever gets closed).

If you don''t Close/Dispose objects that support it, your app will use more memory and other system resources, and its behavior may deteriorate. Yes, the garbage collector will still find those objects, and its finalizer thread will eventually Dispose of them, but that typically will be much later.

:)


这篇关于MyObject =新对象的内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆