By Matt Butcher
benchmarks
Microbenchmarking PHP: Switch Statements are Slow
Submitted by matt on Thu, 2011-08-18 14:02There are very good uses for Switch statements. They can be great for nesting logic. But sometimes they are used as a way to (essentially) map a name to a value. In such a scenario, the body of the case is just a simple assignment.
After noticing this pattern a lot recently, I thought I'd benchmark it against the obvious replacement candidate: a hash table lookup. PHP arrays are more like ordered hash tables. For that reason, they provide very fast random access. Are they faster than a switch statement?
I ran two tests. In the first case, I assumed no default. In the second, I assumed a default. The conclusion: Arrays are faster. Read on for the details.
A Set of Objects in PHP: Arrays vs. SplObjectStorage
Submitted by matt on Fri, 2009-05-29 15:50One of my projects, QueryPath, performs many tasks that require maintaining a set of unique objects. In my quest to optimize QueryPath, I have been looking into various ways of efficiently storing sets of objects in a way that provides expedient containment checks. In other words, I want a data structure that keeps a list of unique objects, and can quickly tell me if some object is present in that list. The ability to loop through the contents of the list is also necessary.
Recently I narrowed the list of candidates down to two methods:
- Use good old fashioned arrays to emulate a hash set.
- Use the SPLObjectStorage system present in PHP 5.2 and up.
Before implementing anything directly in QueryPath, I first set out designing the two methods, and then ran some micro-benchmarks (with Crell's help) on the pair of methods. To say that the results were surprising is an understatement. The benchmarks will likely change the way I structure future code, both inside and outside of Drupal.








