PHP Memory Usage and Performance Improvements Tips
Tags: performance, php
Published: 2021-09-09 15:34:50

---
canonical_url: https://rafael.bernard-araujo.com/php-memory-usage-and-performance-improvements-tips.php
---

Memory usage and performance improvements make everybody happier, from end-user to cloud and infrastructure engineers. And they are all right, and this is an optimization that we should try to achieve as much as possible.

I am also keeping this page for a reference to my future self because we cannot rely too much on our memory, and that will be a good reference I want to re-visit. I will make constant updates on this page. Let's have fun.

## [Use objects with declared properties over array](https://www.slideshare.net/nikita_ppv/php-performance-trivia/31)

Arrays have a larger footprint to avoid constant memory pointers reassignments. It then reserves large amounts of memory when more elements or indexes are added.

![Image for array vs object memory usage](https://rafael.bernard-araujo.com/wp-content/uploads/2021/09/php-performance-trivia-32-1024-150x150.webp)

## [Be careful to self-referencing that would prevent garbage collector from work](https://www.slideshare.net/nikita_ppv/php-performance-trivia/39)

Garbage collector is working as expected when the internal reference count (how may times a value is used) reaches zero:

```php
$x = "foobar";	// refcount = 1
$y = $x;		// refcount = 2
unset($x);		// refcount = 1
unset($y);		// refcount = 0 -> garbage collector will be happy ==> Destroy!
```

But self-referencing can be tricky:

```php
$x = [];			// refcount = 1
$x[0] =& $x;	    // refcount = 2
unset($x);		    // refcount = 1
					// It will never come to zero due to cycle
```

Cycle collector will eventually destroy it, but it will hang on memory for a while anyway.

## Sprintf vs double/single quote concatenation

A very common use case is string concatenation or interpolation when you want to add a variable into a static string. It is interesting to note that:

If you have PHP &lt; 7.4, use double-quote interpolation or single quote concatenation over `sprintf` function.

```php
<?php 

$this->start($loop);

ob_start();

for ($i = 0; $i < $this->loop; ++$i) {
    print 'Lorem '.$i.' ipsum dolor sit amet, consectetur adipiscing elit. Proin malesuada, nisl sit amet congue blandit';
}

ob_end_clean();

return $this->end();
```

If you have PHP greater than 7.4, use `sprintf`:
```php
<?php 

$this->start($loop);

for ($i = 0; $i < $this->loop; ++$i) {
    $value = sprintf('Lorem %s ipsum dolor sit amet, consectetur adipiscing elit. Proin malesuada, nisl sit amet congue blandit', $i);
}

return $this->end();
```

- https://php.lito.com.es/test/compare/SprintfTest/PrintSingleQuoteCodeConcatTest
- https://php.lito.com.es/test/compare/SprintfTest/PrintDoubleQuoteCodeTest

## [PHP Benchmarking](https://www.phpbench.com/)

> PHPBench.com was constructed as a way to open people's eyes to the fact that not every PHP code snippet will run at the same speed. You may be surprised at the results that this page generates, but that is ok. This page was also created so that you would be able to find discovery in these statistics and then maybe re-run these tests in your own server environment to play around with this idea yourself, by using the code examples (these code examples are automatically generated and as the code in my .php files change, so do they).

## [PHP benchmarks and optimizations](https://php.lito.com.es/)

> Collection of tests and benchmarks for common operations in PHP. Tests run on several versions of PHP. There is an option to compare different solutions for the same problem to compare performances between them, such as checking values with `isset` against `!empty`.