Skip to content

Core\Budget::memoryLimit

Core\Budget::memoryLimit(): uint

Returns the largest amount of memory this program may use, in bytes.

The person who runs the server sets this limit, and your program cannot change it. When nobody sets it, the limit is 128M. A program that goes over the limit is stopped with an error. Read this number together with Core\Budget::memoryHeld to see how much room is left, or with Core\Budget::memoryPeak to see how close the program came.

Good to know: the result is 0 when nvs.toml sets memory = false, so this program has no limit. Test for 0 first. Without that test, a program that may use as much memory as it likes looks like a program that is already over its limit.

Return value

Returns uint. The limit in bytes. It is 0 when the request has no memory limit.

Examples

Does this program have a limit

<?nvs
// Shows the first thing to do with the limit: find out whether there is one.
// The limit is a number of bytes, and it is 0 when the program may use as much
// memory as it likes.
uint $limit = Core\Budget::memoryLimit();
if ($limit == 0) {
echo "this program has no memory limit\n";
} else {
// Programs usually run with a limit, so this is the line that prints.
echo "this program has a memory limit\n";
}
Output
this program has a memory limit

How much room is left

<?nvs
// Shows how much memory this program may still use. Take the memory the
// program is using away from the limit, and what is left is the room it has.
uint $limit = Core\Budget::memoryLimit();
uint $held = Core\Budget::memoryHeld();
if ($limit == 0) {
echo "there is no limit, so there is no number to give\n";
} else {
uint $room = $limit - $held;
// A program that has just started uses very little, so nearly all of the
// limit is still free. This prints "more than half of the limit is free".
echo $room * 2 > $limit
? "more than half of the limit is free\n"
: "less than half of the limit is free\n";
}
Output
more than half of the limit is free

Refusing a job that will not fit

<?nvs
// Shows how a program decides whether it can take on a large job. It works out
// how much memory the job needs, and compares that with the limit before it
// starts.
// This job reads a file of about 40 MB into memory.
uint $needed = (40 * 1048576) as uint;
uint $limit = Core\Budget::memoryLimit();
uint $held = Core\Budget::memoryHeld();
// A program with no limit may always go ahead.
bool $fits = true;
if ($limit > 0) {
// The job may use three quarters of the limit at most. The last quarter
// stays free for everything else the program does.
$fits = ($held + $needed) * 4 < $limit * 3;
}
if ($fits) {
echo "reading the file\n";
} else {
echo "the file is too large for this program\n";
}
Output
reading the file