c# - 如何在 C# 中获取内存 MS Windows 7 的当前页面大小?

标签 c# .net memory memory-management

如何在C#中获取内存MS Windows 7的当前页面大小?

在某些情况下,我们需要它以最佳方式分配内存。

谢谢!

更新:这是一个示例代码...我对行 byte[] buffer = new byte[4096];

有一些疑问
// Assign values to these objects here so that they can
// be referenced in the finally block
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;

try
{
    response = request.EndGetResponse(result);

    if (response != null)
    {
        // Once the WebResponse object has been retrieved, get the stream object associated with the response's data
        remoteStream = response.GetResponseStream();

        // Create the local file
        string pathToSaveFile = Path.Combine(FileManager.GetFolderContent(), TaskResult.ContentItem.FileName);
        localStream = File.Create(pathToSaveFile);

        // Allocate a 1k buffer http://en.wikipedia.org/wiki/Page_(computer_memory)
        byte[] buffer = new byte[4096];      
        int bytesRead;

        // Simple do/while loop to read from stream until no bytes are returned
        do
        {
            // Read data (up to 1k) from the stream
            bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

最佳答案

如果您使用的是 C# 4.0,则存在内部使用 GetSystemInfo 的属性 Environment.SystemPageSize。我以前从未见过它,因为它是新的。

http://msdn.microsoft.com/en-us/library/system.environment.systempagesize.aspx

在 C 中你可以这样写。

#include <windows.h>
int main(void) {
    SYSTEM_INFO si;
    GetSystemInfo(&si);

    printf("The page size for this system is %u bytes.\n", si.dwPageSize);

    return 0;
}

然后,您可以使用P/INVOKE 调用GetSystemInfo。 看看http://www.pinvoke.net/default.aspx/kernel32.getsysteminfo

我还必须补充一点,分配页面大小字节的数组并不是最佳选择。

首先,C#内存是可以移动的,C#使用了compacting generational garbage collector。 没有关于数据分配位置的任何信息。

其次,C#中的数组可以由不连续的内存区域组成!数组连续存储在虚拟内存中,但连续的虚拟内存不是连续的物理内存。

第三,C#中的数组数据结构比内容本身多占用一些字节(它存储数组大小和其他信息)。如果您分配页面大小的字节数,使用数组几乎总是会切换页面!

我认为这种优化可以是非优化。

通常,C# 数组在不需要使用页面大小拆分内存的情况下性能非常好。

如果您确实需要精确分配数据,则需要使用固定数组或 Marshal 分配,但这会减慢垃圾收集器的速度。

我会说最好只使用数组而不考虑太多页面大小。

关于c# - 如何在 C# 中获取内存 MS Windows 7 的当前页面大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850385/

相关文章:

c# - 在方法参数中接受一组有限的子类型

c# - 使用 WCF 和 C# (F#) 收集类似散点的操作

c# - 哪个运行时性能更快 : WPF or Winforms?

c# - 如果为 null,则使用 null 条件运算符将值设置为 0

c# - 如何在 C# 中复制数组的值 n 次

c++ - 如果我在使用新程序和结束程序分配数据后没有调用 delete 运算符,会发生什么情况?

sql - 与 DBMS 的内存通信

c - realloc 不为下一个结构分配内存

c# - 如何以编程方式查找 Windows 桌面应用程序是否正在 Windows 手持设备上使用

c# - 当两个类之间存在多个不同(一对多、多对多)关系时如何注释模型类