addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscontroller-playcredit-cardcrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobe--smallglobegmailgooglegroupshelp-with-circleimageimagesinstagramFill 1launch-new-window--smalllight-bulblinklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonprintShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

The Denver Linux, Apache, MySQL and PHP (LAMP) Meetup Group Message Board › PHP code efficiency tradeoffs

PHP code efficiency tradeoffs

A former member
Post #: 29
One of the suggestions at the April meeting was to replace preg_split('/\s*,\*/', $string)
with explode(',', $string).

In the context I was using it, I also want to discard blank space, so the actual equivalent expression would be array_map('trim', explode(',', $string)).

Appreciate the suggestion because it got me to get off my but and install xdebug and test the variants:

To my surprise, preg_split wins by about 3 to 1:

Start: 0.000454902648926
100000 preg_split's(regx, str): 0.358952999115
100000 array_map(trim, explode(',', str)): 1.36321091652
100000 preg_split's(regx, str): 1.71743583679
100000 array_map(trim, explode(',', str)): 2.71812105179
100000 preg_split's(regx, str): 3.07263684273
100000 array_map(trim, explode(',', str)): 4.07095789909
100000 preg_split's(regx, str): 4.42269992828
100000 array_map(trim, explode(',', str)): 5.42294383049

Here's the code. [I haven't read it, so please look it over and see if I goofed]

$str = 'this, is , a , string, with , commas, in ,it';
$count = 100000;
$passes = 4;
echo "Start: " . xdebug_time_index() . "\n";
for ($pass=0;$pass<$passes;$pass++) {
for ($i=0;$i<$count;$i++) {
$v = preg_split('/^\s*,\s*/', $str);
echo "$count preg_split's(regx, str): " . xdebug_time_index() . "\n";
for ($i=0;$i<$count;$i++) {
$v = array_map('trim', explode(',', $str));
echo "$count array_map(trim, explode(',', str)): " . xdebug_time_index() ."\n";
A former member
Post #: 1

I like your style of coding -- thanks for the tips and for following-up the discussion with this proof-of-concept and profiling.

-Wil Moore III
A former member
Post #: 12
The explode Vs. preg_split is definitely one of those unintuitive surprises, but there is also the split/spliti functions which can be marginally faster then preg_split for simple REGEX.

This definitely should be added to the PHP landmines question on StackOverflow.
Powered by mvnForum

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy