减少内存使用的一些技巧是什么.NET应用程序?考虑下面的简单C语言程序.
class Program
{
static void Main(string[] args)
{
Console.ReadLine();
}
}
在x64的release模式下编译并在Visual Studio外部运行时,任务管理器报告以下内容:
Working Set: 9364k
Private Working Set: 2500k
Commit Size: 17480k
如果只为x86编译,会更好一些:
Working Set: 5888k
Private Working Set: 1280k
Commit Size: 7012k
然后,我try 了以下程序,该程序执行相同的操作,但会在运行时初始化后try 调整进程大小:
class Program
{
static void Main(string[] args)
{
minimizeMemory();
Console.ReadLine();
}
private static void minimizeMemory()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle,
(UIntPtr) 0xFFFFFFFF, (UIntPtr)0xFFFFFFFF);
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetProcessWorkingSetSize(IntPtr process,
UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize);
}
Visual Studio外部x86 Release上的结果:
Working Set: 2300k
Private Working Set: 964k
Commit Size: 8408k
Which is a little better, but it still seems excessive for such a simple program. Are there any tricks to make a C# process a bit leaner? I'm writing a program that's designed to run in the background most of the time. I'm already doing any user interface stuff in a separate Application Domain which means the user interface stuff can be safely unloaded, but taking up 10 MB when it's just sitting in the background seems excessive.
P.S. As to why I would care --- (Power)users tend to worry about these things. Even if it has nearly no effect on performance, semi-tech-savvy users (my target audience) tend to go into hissy fits about background application memory usage. Even I freak when I see Adobe Updater taking 11 MB of memory and feel soothed by the calming touch of Foobar2000, which can take under 6 MB even when playing. I know in modern operating systems, this stuff really doesn't matter that much technically, but that doesn't mean it doesn't have an affect on perception.