| Optimizing Your PHP Scripts |
| Article Index |
|---|
| Optimizing Your PHP Scripts |
| Page 2 |
| Page 3 |
| Page 4 |
| Page 5 |
| Page 6 |
| Page 7 |
| Page 8 |
| Page 9 |
| Page 10 |
| Page 11 |
| Page 12 |
NOTEMany factors contribute to how a particular script will perform. It is important to note that generally there is a standard deviation of +- 5% on any time measurement taken. |
Regular Expressions
One of the most common optimization mistakes made by PHP developers is the overuse or misuse of regular expressions in their PHP scripts. Compared to other text-manipulation operations, using regular expressions represents the most costly operation that can be done. Thus, any use of regular expressions should be done with great care. To illustrate this, consider searching 10,000 random strings for any combination of three characters "a" through "g" (that is, agb, bbb, cab, and so on).
I will compare the two types of regular expression solutions provided by the ereg() and preg_match() functions. Let's start with the code required to solve the problem using ereg():
for($i = 0; $i < 10000; $i++) {
if(ereg(".*[abcdefg]{3}.*", $strings[$i])) {
$found++;
}
}
Similarly, here is the solution to the problem using the preg_match() function instead:
for($i = 0; $i < 10000; $i++) {
if(preg_match("/.*[abcdefg]{3}.*/", $strings[$i])) {
$found++;
}
}
When profiling these two methods against each other (the ereg() method is #1 and preg_match is #2), here is how they measured up:
Method one took 0.21848797798157 seconds.
Method two took 0.15077900886536 seconds.
Method two was faster than Method one by 30.99%
| Users' Comments (0) |
|
No comment posted








