Laravel's collect()->join() method vs implode() | Benchmark
Laravel offers a convenience to join an array such as
[one,two,three] into a string like this:
'one, two and three', which takes a little extra code in PHP native, but is also quite faster in PHP native. This blog post was inspired by a tweet by @ecrmnn.
Laravel collect->join() code:
This will yield the string
one, two and three.
'one', 'two', 'three']; $str = collect($array)->join(', ', ' and ');$array = [
Native php array_pop & implode()
This will also yield the string
one, two and three.
'one', 'two', 'three']; $last = array_pop($array); $str = implode(', ', $array).' and '.$last;$array = [
In my benchmark on php 7.4 with 1,000,000 iterations:
- collect/join: 0.6556 seconds
- pop/implode : 0.0472 seconds
php 8.0 was similar.
When I re-ran the laravel benchmark with JUST
collect($array), and did NOT
join(), it took 0.1113 seconds.
The collect approach comes out to 0.656 μs (micro seconds) per iteration.
collect()->join()is quite readable & for some may be easier to maintain.
- I think it's probably easier for a new coder or someone new to php to understand.
- Laravel Collections also provide other convenience methods, so you might use the same collection object for multiple things.
- It is about 14 times slower than the php native
- Code portability. If you ever decide to stop using laravel, this will break.
- Laravel comes with many dependencies. But i doubt you'd use their collections unless you were using laravel already anyway. Also, you may be able to just install illuminate collections
- Built-in to php. No dependencies to install
- significantly faster
- saves energy
- some may find the native php approach more readable
- an extra line of code
- not as 'cool'
The actual amount of cpu time is negligible on modern hardware. I suspect the energy cost for your webhost probably won't be much bothered either.
Ultimately, whatever you like better is probably fine, if you think you're going to use laravel long term. If you have plans to kick laravel, i'd suggest the native approach. You could also throw the native approach into a function like
fancy_implode if you need it in multiple places.
I personally prefer the native php implementation. I have feelings about it, and i have a hard time saying why i actually care. I think my main issue with collect/join is the direction a lot of software has gone in as time moves forward. We develop more and more layers of abstraction. We rely on fast hardware to run slow software. We get farther and farther from what the computer is actually doing.
I don't think abstraction is bad. I do value developer experience. I even sometimes write & use slow software myself because i like it. Just. Something about this bothers me & it's hard to explain why.