Memory

A memory utility that is able to convert between various order of magnitude. It uses bytesopen in new window as its lowest value and offers support upto Exabyte or Exbibyteopen in new window. In addition, it is also able to format a size to a "human-readable".

SIopen in new window "decimal" and "binary" values are supported.

Example

use Aedart\Utils\Memory;

$bytes = 5_300_000_000;

echo Memory::unit($bytes)->binaryFormat(); // 4.9 GiB
echo Memory::unit($bytes)->decimalFormat(); // 5.3 GB

Create

From Bytes

To create a new memory unit instance from bytes, use the static unit() method.

$bytes = 2_000_000;
$unit = Memory::unit($bytes);

From String

You can also create a new instance from a string.

$unit = Memory::from('1.48 kb');

echo $unit->bytes(); // 1480

The accepted format has to match the following:

format = value space unit;
value = INT | FLOAT;
space = "" | " "; // optional whitespace character
unit = (unit symbol or name);

Given the above shown format, the following strings can all be parsed into a value unit.

$a = Memory::from('28 b');
$b = Memory::from('1.48 kb');
$c = Memory::from('3 megabyte');
$d = Memory::from('2 MiB');
$e = Memory::from('1.1gigabyte');
$f = Memory::from('5 terabytes');
$g = Memory::from('2.35 PB');
// ...etc

From Other Values

Lastly, you can also create a unit instance from other units than bytes.

$a = Memory::fromKibibyte(1540);
$b = Memory::fromMegabyte(2.4);
$c = Memory::fromGibibyte(1.33)
// ...etc

Convert

The memory unit offers various conversion methods.

$gibibyte = Memory::fromGibibyte(1.33);

echo $gibibyte->toMegabyte(); // 1428.1
echo $gibibyte->toLegacyMegabyte(); // 1361.9
// ...etc

You can also use the to() method, to specify a string unit to convert the unit into:

$unit = Memory::unit(5_340_000_000); // bytes

echo $unit->to('gigabyte', 2); // 5.34

Note The second argument is the rounding precision.

Formatting

To format a unit to a "human-readable" string, you can use either of the following methods:

$unit->binaryFormat();
$unit->decimalFormat();
$unit->legacyFormat() // binary using legacy metric name
$unit->format(); // Defaults to "binary"

See wikiopen in new window, and source code for details.

Snapshot

The snapshot() method returns the current amount of memory used by PHP.

$snapshot = Memory::snapshot();

echo $snapshot->bytes(); // 544812

The method also accepts a boolean $reset argument, which will automatically reset the peak memoryopen in new window, before capturing the snapshot.

$snapshot = Memory::snapshot(true);

echo $snapshot->bytes(); // 527729

Onward

Please review the source code of Aedart\Utils\Memory and Aedart\Utils\Memory\Unit for additional information.