PHP: Array vs ArrayObject benchmarking

Some measurements on Arrays vs ArrayObjects found among gist users. Just going to bring it here, in case gist dissappears.

# php -v
PHP 5.3.6 (cli) (built: Mar 17 2011 20:58:15)
Copyright (c) 1997-2011 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies

# echo '<?php $s = array(); for($x=0;$x<1000;$x++){ $s[] = array("name"=>"Adam","age"=>35); }; echo memory_get_peak_usage(); ' | php

# echo '<?php $s = array(); for($x=0;$x<1000;$x++){ $o = new ArrayObject; $o->name = "Adam";  $o->age = 35;  $s[] = $o;} echo memory_get_peak_usage(); ' | php

# time echo '<?php $s = array(); for($x=0;$x<100000;$x++){ $o = new ArrayObject; $o->name = "Adam";  $o->age = 35;  $s[] = $o;} echo memory_get_peak_usage(); ' | php
real    0m1.448s
user    0m1.208s
sys     0m0.231s

# time echo '<?php $s = array(); for($x=0;$x<100000;$x++){ $s[] = array("name"=>"Adam","age"=>35); }; echo memory_get_peak_usage(); ' | php
real    0m0.525s
user    0m0.429s
sys     0m0.092s

We can conclude the following at least in PHP 5.6:

  • Winner for Speed: Arrays are faster than objects (with undefined or defined properties)
  • Winner for Memory: Objects with defined properties use less memory, 50%+ less than objects with undefined properties, only slightly less than Arrays

Ordered Fastest to Slowest in Speed for 100,000 items:

  • 0.107s – Arrays
  • 0.163s – Objects with undefined properties
  • 1.190s – Objects with defined properties

Ordered Least to Most Memory Usage for 1,000 items:

  • ~583kb – Objects with defined properties
  • ~807kb – Arrays
  • ~1.1mb – Objects with undefined properties

Code elegance: one of those days


Ah, it’s just one of those days! It seems that I can wail about this topic in non-stop mode. Why do people overcomplicate problem domain with sophisticated solution. Have you tried to read what you wrote the day after? A week after? No? Then, read it, and try to guess what you’ve been trying to achieve! And at the meantime, read this Programmers Stackexchange topic on Code Elegance.

Not enough?


how to read books
Read and learn