You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

vector嵌套容器内存占用异常原因及优化咨询

关于vector<vector<char>>的内存占用疑问

我通过当前进程的WorkingSetSize分析物理内存占用,该方法经Codeforces验证与本地结果一致,但对vector<vector<char>>的内存占用情况存在理解障碍。

运行环境:Windows 11 x64,MinGW-w64 x86_64 11.3.0,无额外编译选项。

测试代码如下:

#include <iostream>
#include <vector>
#include <windows.h>
#include <psapi.h>

SIZE_T toKB(SIZE_T b) { return b / 1024; }

SIZE_T initialMemory = 0;
void initMemory() {
  PROCESS_MEMORY_COUNTERS pmc;
  pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);

  HANDLE hProcess = GetCurrentProcess();
  if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) {
    initialMemory = pmc.WorkingSetSize;
  }
}
void printMemory() {
  PROCESS_MEMORY_COUNTERS pmc;
  pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);

  HANDLE hProcess = GetCurrentProcess();
  if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) {
    std::cout << toKB(pmc.WorkingSetSize - initialMemory) << "KB" << std::endl;
  }

  CloseHandle(hProcess);
}

int main() {
  int N = 100'000;
  int M = 15;

  printMemory();
  initMemory();
  printMemory(); // 0B

  std::vector<std::vector<int>> vec(N, std::vector<int>(M));
  printMemory(); // Result
}

实验结果:

For vector<vector<char>>
M:  1 ~  8 ->  3956KB
M:  9 ~ 24 ->  5584KB (+1628KB)
M: 25 ~ 40 ->  7140KB (+1556KB)
M: 41 ~ 56 ->  8748KB (+1608KB)

For vector<vector<int>>
M:  1 ~  2 ->  3956KB
M:  3 ~  6 ->  5584KB (+1628KB)
M:  7 ~ 10 ->  7140KB (+1556KB)
M: 11 ~ 14 ->  8748KB (+1608KB)

我原本推测vector<vector<char>>(N=10^5)的内存占用应为(2400 + M*100)KB,但实验结果显示:

  • 容量1~8的vector<char>占用16B
  • 容量9~24的vector<char>占用32B

另外,我做了使用new []的对照实验,结果符合我的内存模型推测。

现提出以下疑问:

  • 占用8B的神秘内存块是什么?
  • 内存分配为何以16B为粒度?
  • 是否存在预分配?如何优化内存占用?(注:需运行时长度N,不使用push_back)

内容的提问来源于stack exchange,提问作者Simelvia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 09:23:39