note 57816 deleted from function.explode by betz

From: Date: Sat, 11 Feb 2006 16:37:20 +0000
Subject: note 57816 deleted from function.explode by betz
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-103510@lists.php.net to get a copy of this message
Note Submitter: michael dot martinek at gmail dot com ---- >> richardkmiller at gmail dot com I was also looking for an explode() function that would allow you to specify an encapsulation character. I went ahead and developed one of my own based roughly off yours. My version of it is faster in the sense that: - It does not do string = string + character. This creates a new copy in memory each time. - It does not calculate the length of the source string on each for() iteration. Memory/processing time trade-off. Additionally, it retains the same features provided through your explode2() function. Namely, the fact that you can specify your own delimiter character and allow for encapsulation characters to be passed. My version will allow you to specify your own encapsulation character. I've run 4 tests on my Linux Server, running 800MHz w/ 512 SD-RAM. Linux beta 2.6.12-1.1447_FC4 #1, PHP 5.0.4 (cli) (built: Aug 17 2005 09:53:54). The average of the time results are as follows: explode_quote average time 0..500000 76.704669952393 explode2() average time 0..500000 113.08254504204 The time calculation is done with a microtime() before the 500,000 loop and then microtime() - startTime upon completion. Four tests were run on each version, and the averages used. Here's the code: <?php function explode_quote($ADelim, $AString, $AEncap = '"') { $retval = array(); //if we have an empty string, don't even bother processing if (empty($AString)) return $retval; //calculate source length and initialize some variables $srcLength = strlen($AString); $insideEncap = false; //0..X string indexing in PHP, we'll be reading +1 $lastPos = -1; for ($x=0;$x<$srcLength;$x++) { if ($AString[$x]==$AEncap) $insideEncap = !$insideEncap; elseif (!$insideEncap && $AString[$x]==$ADelim) { $retval[] = substr($AString, $lastPos+1, $x-$lastPos-1); $lastPos = $x; } } //if string doesn't end with delimiter, then throw remaining data to result if ($lastPos!=$srcLength) $retval[] = substr($AString, $lastPos+1, $srcLength); return $retval; } ?> If anyone decides to run any of their own speed tests, ensure to use set_time_limit(0), otherwise it'll stop after your configured max_execution_time. Rather than string = string + data, this version will just save the position of the most recent delimiter. Once it hits another delimiter, it will copy a section of the string from the previous-found delimiter. The result is one memory allocation for the string, rather than many for s .= d.

« previous php.notes (#103510) next »