Benefits of reserving vs. committing+reserving memory using VirtualAlloc on large arrays

风流意气都作罢 提交于 2019-12-05 14:24:39

The difference is that commit "backs" the memory against the page file. To give an example:

  1. Given 2GB of physical ram and 2GB of swap (assume fixed-size swap for this purpose).
  2. Reserve 6GB - OK.
  3. Commit first 2GB - OK.
  4. Commit remaining 4GB - fails.
  5. Extend swap file to 8GB
  6. Commit remaining 4GB - succeeds.

The reason for using MEM_COMMIT would primarily be for runtime error suppression (app stability). If you have a process that commits pages on-demand then there's always a chance that a commit along-the-way could fail if it exceeds amount of memory+swap available. When memory has been backed by the page file then you have a strong guarantee that the memory is available for use from now until the point that you release it.

There's a number of reasons to go one way or the other, and I don't think there's any perfect science to deciding which. MEM_RESERVE alone is only needed for very large sparse array scenarios, ex: multi-gigabyte array which has at most 25-33% utilization (a popular technique for accelerating hash tables, etc).

Almost everything else is gray area where you could probably go either way -- MEM_COMMIT up-front would make your own app a little more stable and essentially give it priority to physical ram over competing apps that might allocate on-demand. (if you grab the ram first then your app will be the last left standing when physical memory is exhausted) At the same time, if you're not actually using all that ram then you may end up limiting the multi-tasking potential of your client's machine or causing unnecessary wasted disk space via a growing page file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!