在 Linux + C++ 环境下,“省内存”通常从 编译期、运行期、数据结构、系统配置 四个层面来做。下面按实用程度给你一份清单。
-Os # 优化尺寸而非速度
-ffunction-sections
-fdata-sections
-Wl,--gc-sections # 删除未使用代码
示例:
g++ -Os -ffunction-sections -fdata-sections -Wl,--gc-sections main.cpp
-s # 去掉符号表
-strip # 或编译后 strip
musl libc 比 glibc 更省内存ulimit -v 100000 # 限制虚拟内存 100MB
或代码中:
#include <sys/resource.h>
setrlimit(RLIMIT_AS, ...);
不同场景选不同 allocator:
| 分配器 | 特点 |
|---|---|
| glibc (ptmalloc) | 默认,一般 |
| tcmalloc | 多线程友好 |
| jemalloc | 低碎片 |
| mimalloc | 极快、低开销 |
示例(jemalloc):
LD_PRELOAD=/usr/lib/libjemalloc.so ./app
❌ 错误示例:
std::string s = "hello" + "world";
✅ 更好:
std::string s;
s.reserve(11);
s += "hello";
s += "world";
| 场景 | 推荐 |
|---|---|
| 小数据 | std::array |
| 只读表 | std::vector |
| 大量查找 | flat_hash_map |
| 不需要排序 | 不要用 std::map |
class Pool {
std::vector<Obj> pool;
};
避免频繁 new/delete
std::movestd::string_viewconst &sysctl vm.swappiness=10
ubuntualpine 或 distroless#include <cstdio>
int main() {
printf("hello\n");
}
编译:
g++ -Os -s main.cpp -o main
你可以告诉我:
我可以给你针对性优化方案,甚至帮你 review 代码。