Skip to content

Instantly share code, notes, and snippets.

@alkavan
Last active April 10, 2018 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alkavan/4d310c63e831e484108bf519c8232e09 to your computer and use it in GitHub Desktop.
Save alkavan/4d310c63e831e484108bf519c8232e09 to your computer and use it in GitHub Desktop.
PHP 7.2 Anonymous Class vs Array - Memory Test

PHP 7.2 real app usage:

public function jsonSerialize()
    {
        $m1 = memory_get_usage();
        $json_class = new class implements SpecExportInterface {
            public $id;
            public $status;
            public $code;
            public $title;
            public $source;
            public $links;
        };
        $m2 = memory_get_usage();
        $json_class->id     = $this->id;
        $json_class->status = $this->status;
        $json_class->code   = $this->code;
        $json_class->title  = $this->title;
        $json_class->source = $this->source;
        $json_class->links  = $this->links;
        $m3 = memory_get_usage();
        $a1 = [];
        $m4 = memory_get_usage();
        $a1['id']     = $this->id;
        $a1['status'] = $this->id;
        $a1['code']   = $this->id;
        $a1['title']  = $this->id;
        $a1['source'] = $this->id;
        $a1['links']  = $this->id;
        $a1['id']     = $this->id;
        $m5 = memory_get_usage();

        echo 'class create:' . ($m2-$m1) . '</br>'
            .'class assign:'  . ($m3-$m2) . '</br>'
            .'array create:' . ($m4-$m3) . '</br>'
            .'array assign:'  . ($m5-$m4) . '</br>'
            ;die;

        return $json_class;
    }

Results:

class create: 168 bytes
class assign: 0 bytes
array create: 0 bytes
array assign: 376 bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment