2010-03-04 20 views
3

有一些關於 How to get object size in memory ? 的文章,但它們沒有解釋如何獲取內存中對象的大小。在內存中獲取DataTable或ArrayList的大小

當我使用:

System.Runtime.InteropServices.Marshal.SizeOf(arrayListObject)

我得到錯誤:

Type 'System.Collections.ArrayList' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

我也無法得到可用的存儲量,becouse我想執行上與Web應用程序這個計算很多線程,所以需要知道具體對象需要多少內存。

+1

除非你仍然停留在.NET 1.1,否則不應該使用'ArrayList'。如果您需要包含任何對象的列表,請使用'列表'。 – 2010-03-04 12:03:46

+0

問題不是關於使用對象的方式,現在我正在使用DataTable – 2010-03-09 05:19:39

回答

1

如果你想知道這可能是因爲可能的優化:使用內存分析器。

+0

不,我不想知道它是爲了優化,我想知道我的DataTable何時增長太多,才能激發事件。 – 2010-03-09 05:20:31

2

你想知道在代碼管理對象的內存大小 - 根據this博客條目,這是不可能的。

您需要使用內存分析器來執行此操作(如Ants profiler)。

+0

我不想使用分析器,我需要知道大小以觸發警報/事件或某事 – 2010-03-09 05:21:13

0

那麼如何序列化DataTable,然後檢查其長度?

System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
System.IO.MemoryStream stream = new System.IO.MemoryStream(); 
formatter.Serialize(stream, YourDataTable); 
long length = stream.Length;