Following up on his previous post about anonymous classes and a factory to generate them, Mark Baker has posted about the results of some additional research he’s done on the topic and four options he’s come up with.
A week or so ago, I published an article entitled “In Search of an Anonymous Class Factory” about my efforts at writing a “factory” for PHP7’s new Anonymous Classes (extending a named concrete base class, and assigning Traits to it dynamically); and about how I subsequently discovered the expensive memory demands of my original factory code, and then rewrote it using a different and (hopefully) more memory-efficient approach.
Since then, I’ve run some tests for memory usage and timings to assess just how inefficient my first attempt at the factory code was, and whether the new version of the factory really was better than the original.
His four options that finally worked somewhat as he’d wanted were:
- A factory that returns an instance of a concrete class using the traits he wants
- A factory that returns an anonymous class extending a concrete class that uses the traits
- His original Anonymous Class factory and extending the result with the traits
- His second version of the Anonymous Class factory that creates the instance, caches it and returns a clone
He also includes the code he used to run the tests of each factory method and shares some of the resulting benchmarks (with a few surprises).