marc-mabe / php-enum

Simple and fast implementation of enumerations with native PHP
BSD 3-Clause "New" or "Revised" License
464 stars 36 forks source link

EnumSet IteratorAggregate using Generator #110

Closed marc-mabe closed 5 years ago

marc-mabe commented 5 years ago
+----------------+-------------------+--------------+--------------------+-----------------------+
| benchmark      | subject           | tag:4.x:mean | tag:generator:mean | tag:newInterator:mean |
+----------------+-------------------+--------------+--------------------+-----------------------+
| EnumSet66Bench | benchIterateFull  | 83.580μs     | 46.399μs           | 100.906μs             |
| EnumSet66Bench | benchIterateEmpty | 0.510μs      | 10.972μs           | 18.026μs              |
| EnumSet32Bench | benchIterateFull  | 33.086μs     | 18.721μs           | 41.721μs              |
| EnumSet32Bench | benchIterateEmpty | 0.401μs      | 3.688μs            | 7.150μs               |
+----------------+-------------------+--------------+--------------------+-----------------------+

Using a Generator makes it even faster iterating through elements of an EnumSet as a direct Iterator implementation. Instantiating the Generator seems to take more time (and memory) as seen in iterating an empty EnumSet but I think this is reasonable.

But using a generator has some small downsides but in my opinion all of them are negligible:

ping @prolic

marc-mabe commented 5 years ago

Even further optimized:

+----------------+-------------------+--------------+--------------------+-----------------------+
| benchmark      | subject           | tag:4.x:mean | tag:generator:mean | tag:newInterator:mean |
+----------------+-------------------+--------------+--------------------+-----------------------+
| EnumSet66Bench | benchIterateFull  | 83.580μs     | 35.053μs           | 100.906μs             |
| EnumSet66Bench | benchIterateEmpty | 0.510μs      | 0.571μs            | 18.026μs              |
| EnumSet32Bench | benchIterateFull  | 33.086μs     | 15.915μs           | 41.721μs              |
| EnumSet32Bench | benchIterateEmpty | 0.401μs      | 0.825μs            | 7.150μs               |
+----------------+-------------------+--------------+--------------------+-----------------------+
prolic commented 5 years ago

Love it!

Sidenote: Generator::send/throw is mostly used for coroutines in PHP. I didn't encounter any other use case so far, expect to create nice bugs to make people crazy.