。C#/。NET:字典的内存使用情况 [英] C#/.NET: Dictionary memory usage

查看:301
本文介绍了。C#/。NET:字典的内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有保存一组数据的通用词典。我想开始删除项目(我知道如何确定哪些)时,字典的大小,开始占用太多的内存。

什么是最好的方法我的程序来监视使用该词典的RAM?

在字典的每一项都是一个变量的大小。

解决方案

工作了每个项目的规模和乘以 Dictionary.Count

一种方式显示这里

  

这是近似的方式来确定   对象使用的存储器的大小可以是   通过检查总内存中完成   前后创作的后   目的。在下面的例子中它   假定你有一类名为foo。

 长StopBytes = 0;
FOO myFoo;

长StartBytes = System.GC.GetTotalMemory(真正的);
myFoo =新富();
StopBytes = System.GC.GetTotalMemory(真正的);
GC.KeepAlive(myFoo); //这确保一个参考对象保持对象在内存

的MessageBox.show(大小是+((长)(StopBytes  -  StartBytes))的ToString());
 

C#有一个sizeof的操作符,就像它在C / C ++,但它返回一个该类型的字段将成为大小。因此,对于引用类型(类,而不是结构),它总是会返回一个指针(4在32位系统)的大小。使用 System.Runtime.InteropServices.Marshal.SizeOf()代替。

I've got a generic Dictionary that holds a bunch of data. I'd like to start removing items (I know how to determine which ones) when the size of the Dictionary starts taking up too much memory.

What's the best way for my program to monitor the RAM used by this Dictionary?

Each item in the Dictionary is a variable size.

解决方案

Work out the size of each item and multiply by the Dictionary.Count

One way is shown here:

An approximate way to determine the size of object usage in memory can be done by checking the total memory before and after the creation of the object. In the following example it is assumed you have a class named foo.

long StopBytes = 0;
foo myFoo;

long StartBytes = System.GC.GetTotalMemory(true);
myFoo = new foo();
StopBytes = System.GC.GetTotalMemory(true);
GC.KeepAlive(myFoo); // This ensures a reference to object keeps object in memory

MessageBox.Show("Size is " + ((long)(StopBytes - StartBytes)).ToString());

C# has a 'sizeof' operator that works like it does in C/C++, however it returns the size that a field of that type will be. Thus for reference types (class, not struct), it will always return the size of a pointer (4 on 32 bit systems). Use System.Runtime.InteropServices.Marshal.SizeOf() instead.

这篇关于。C#/。NET:字典的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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