V8的内存限制
- V8把内存分为「新生代(New Space)」和 「老生代 (Old Space)」。新生代中的对象为存活时间较短的对象,老生代中的对象为存活时间较长或常驻内存的对象;–max_old_space_size改变的是老生代的内存大小,单位为M;–max_new_space_size改变的是新生代的内存大小,单位为K;
- 《深入浅出nodejs》书中“内存控制章节”说明,64位系统约为1.4GB,32位系统约为0.7GB;
- 书中说明,Buffer是基于c++,其内存是Node的C++层面提供的,不受V8内存限制;
- 我的测试结果:Buffer的内存不能大于2G,否则会内存泄漏,Array不能大于4G,这点我不太明白;为什么Buffer会有内存限制呢?而Array的限制却为4G,不应该是1.4G么?测试代码如下:
// 2G,会报错:RangeError: Invalid typed array length
new Buffer(2*1024*1024*1024)
// 2G-1,正常,不会报错
new Buffer(2*1024*1024*1024 - 1)
// 4G,会报错:RangeError: Invalid typed array le#ngth
new Array(4*1024*1024*1024)
// 4G-1,正常,不会报错
new Array(4*1024*1024*1024-1)
可用案例
[ Math.pow(2, 40) ] // [ 1099511627776 ]
[ -1 ] // [ -1 ]
new ArrayBuffer(Math.pow(2, 32) - 1)
new ArrayBuffer(0)
let a = [];
a.length = Math.max(0, a.length - 1);
let b = new Array(Math.pow(2, 32) - 1);
b.length = Math.min(0xffffffff, b.length + 1);
// 0xffffffff is the hexadecimal notation for 2^32 - 1
// which can also be written as (-1 >>> 0)
不可用案例
new Array(Math.pow(2, 40))
new Array(-1)
new ArrayBuffer(Math.pow(2, 32))
new ArrayBuffer(-1)
let a = [];
a.length = a.length - 1; // set -1 to the length property
let b = new Array(Math.pow(2, 32) - 1);
b.length = b.length + 1; // set 2^32 to the length property
注意:本文归作者所有,未经作者允许,不得转载