A friendly reminder that objects (from classes) are more efficient than arrays.

Unknown
edited November 2018 in Dev & Ops

I ran some quick tests:

  • Create an obj/array of a similar shape 100,000 times.
  • Use random string/number values.
  • PHP 7.2 used.

This is actually the opposite of things were in PHP 5.x so worth noting.

Gist here: https://gist.github.com/charrondev/be56ef53e0408b959eff6d2d911e8c1e

Results

image.png

Takeaways

Objects created from classes in PHP 7.2 (+?):

  • Use less than half the amount of memory than untyped arrays do.
  • Are slightly faster than untyped arrays

The takeaway? Make more value classes! We should not use so many untyped arrays in our code.

Comments

  • Good advice!

    In case it wasn't clear to others reading this: It's important to keep in mind that this isn't "objects/classes are better than arrays", but specifically that well-defined classes are better at storing well-defined data than an associative array would probably be. A poorly-defined class would probably be worse. You can see this by removing the property declarations off the test class in the benchmark files. This will cause them to be dynamically-declared fields (added as they're assigned). The result is objects using 15-20% more memory in the otherwise same benchmarks, with similar increases in execution time.

    tl;dr: Don't start storing everything in a stdClass.

  • I've updated the benchmark to include stdClass. Here's the new results:

    image.png

    TL;DR; Don't use stdClass.

  • Interesting, if I modify test to:

    $s = [];
    class MyArrayObject {
        public $name, $age;
        public function __construct() {
            $this->name = randomString();
            $this->age = rand(1, 100);
        }
    }
    for ($x = 0; $x < 100000; $x++) {
        $s[] = new MyArrayObject();
    }
    echo "Objects only peak memory usage: " . memory_get_peak_usage() . "b\n";
    
    

    it takes even less: 17,588,592