|
| 1 | +// |
| 2 | +// Small program to test the maximum single allocation that Node.js can achieve. |
| 3 | +// This script searches for the larget allocation size. |
| 4 | +// |
| 5 | + |
| 6 | +// |
| 7 | +// Note this program invokes the garbage collector explicitly, so it must be run with the Node.js flag --expose-gc |
| 8 | +// |
| 9 | + |
| 10 | +// |
| 11 | +// Allocate a certain size to test if it can be done. |
| 12 | +// |
| 13 | +var alloc = function (size) { |
| 14 | + return Buffer.allocUnsafe(size); |
| 15 | +}; |
| 16 | + |
| 17 | +// |
| 18 | +// Allocate successively larger sizes, doubling each time until we hit the limit. |
| 19 | +// |
| 20 | +var allocUp = function (startingAllocationSize, allocationStep) { |
| 21 | + |
| 22 | + var lastAllocatedSize = 0; |
| 23 | + var workingAllocationSize = startingAllocationSize; |
| 24 | + var workingAllocationStep = allocationStep; |
| 25 | + |
| 26 | + try { |
| 27 | + |
| 28 | + while (true) { |
| 29 | + console.log("Allocating " + workingAllocationSize); |
| 30 | + |
| 31 | + alloc(workingAllocationSize); |
| 32 | + |
| 33 | + // Successfully allocated. |
| 34 | + lastAllocatedSize = workingAllocationSize; |
| 35 | + |
| 36 | + // Allocate more memory next time. |
| 37 | + workingAllocationSize += allocationStep; |
| 38 | + |
| 39 | + // Double the amount we are trying to allocate. |
| 40 | + allocationStep *= 2; |
| 41 | + |
| 42 | + // Force garbage collection and reclaim. |
| 43 | + global.gc(); |
| 44 | + } |
| 45 | + |
| 46 | + // Infinite loop, never get here. |
| 47 | + } |
| 48 | + catch (err) { // Memory allocation error. |
| 49 | + console.error(err); |
| 50 | + |
| 51 | + console.log('Last successfull allocation: ' + lastAllocatedSize); |
| 52 | + console.log('Attempted to allocate: ' + workingAllocationSize); |
| 53 | + |
| 54 | + return { |
| 55 | + lastAllocatedSize: lastAllocatedSize, |
| 56 | + limit: workingAllocationSize, |
| 57 | + }; |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +var startingAllocationSize = 1024*10; |
| 62 | +var startingAllocationStep = 8; |
| 63 | +var lastResult = null; |
| 64 | +var i = 0; |
| 65 | + |
| 66 | +while (true) { |
| 67 | + var result = allocUp(startingAllocationSize, startingAllocationStep); // Allocate up until we hit a limit. |
| 68 | + console.log(result); |
| 69 | + |
| 70 | + startingAllocationSize = result.lastAllocatedSize; |
| 71 | + |
| 72 | + if (lastResult) { |
| 73 | + var difference = result.limit - result.lastAllocatedSize; |
| 74 | + console.log('Allocation difference ' + difference); |
| 75 | + if (difference <= startingAllocationStep) { |
| 76 | + break; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + if (++i > 10000) { |
| 81 | + break; // Saftey breakout. |
| 82 | + } |
| 83 | + |
| 84 | + lastResult = result; |
| 85 | +} |
| 86 | + |
| 87 | + |
0 commit comments