PHP Benchmark - Indexed Arrays Vs Associative Arrays vs Classes

One of the most common PHP questions I receive is what is the best way to store data: indexed arrays, associative arrays, or classes (most likely with overloading). To answer this question I whipped up a quick little benchmark, which will return the time needed to A) store data via each type, and B) copy data for each type. This is not scientifically accurate by any stretch of the imagination - but I think it gives a pretty good idea which type is the quickest.

The Test

The script will run each loop 10,000 times by default, and this can be set via the $run_amt variable. The test will be run 20 times (set via $num_tests) and the results are added together, averaged, then displayed. You can view the output for each test by setting $verbose to true.

Here’s the script I used.

The Results

The results are in seconds:

Total Time:
Numerical Array: 0.2946305
Associative Array: 0.392692
Class: 0.364164

Averages:
Numerical Array: 0.014731525
Associative Array: 0.0196346
Class: 0.0182082

Conclusion

I tried running it on both my local server and the server that runs this site - and the differences between each data type were pretty much the same. Indexed arrays are the fastest, surprisingly classes (using overloading) were the second fastest, and associative arrays are in last place.

This isn’t very scientific, nor does it measure how much memory each type uses or how much CPU us required - but I think it gives a good idea which type is better.

I think if you’re going to be storing a little bit of data, it doesn’t matter which type you use. The differences were barely there when I ran the test with 100 loops instead of 10,000. However, when storing large amounts of data indexed arrays ($i[1], $i[50], etc) are probably the best choice.

If you can come up with a better test, go for it. I wrote this thing in about 10 minutes at midnight - so I wouldn’t be surprised if there’s a better way to do the benchmark. I have a feeling the results will be fairly similar though.

Please subscribe, or else I will cry. Do you really want to make a programmer cry?

Leave a Reply

Note: By submitting your comment you agree to this blog's comment policy.

If you want a little icon next to your name - sign up for one at Gravatar.