![]() |
|
|
|
|
| 010011010110000101110100011101000010000001000010011101010111010001100011011010000110010101110010 | |
|
PHP: Strings vs. Character ArraysWhich is faster: Using strings, or using char arrays?
Author: M Butcher A common misnomer with PHP is that strings are arrays. While they can be treated like arrays, they are not arrays, and using array functions on them will (justifiably) return an error. But what if you are doing a number of small conditional modifications to a string? Here's a very simple example: what if you are simply consuming a string? Is it faster to convert a string to an array of characters, and then use array manipulation functions, or is it faster to use clumsier string functions? Here's the test I devised to find out. It is a simple comparison of using the substring() function vs. using an array_shift() function. #!/usr/bin/phpThe script above first gets a chunk of random characters from the /dev/urandom device. It then tests two different strategies for consuming a string (Note: we don't do anything with the popped character -- we just throw it away). In the first case, we consume the string by converting it to an array with str_split(), and then repeatedly shifting the array with array_shift(). I cheated. I didn't include the amount of time it took the str_split() function to split the string. Instead, I only counted the amount of time taken to shift the array. On average, running the test on a 3072 character string, this method took about 0.175 seconds. In the second case, I just continually called substr() on the string, chomping off one char at a time. Now, from Java experience, I expected this to be rather time consuming. After all, isn't a string a more complex (== more memory, longer creation time) sort of beast than an array? Well, apparently this is not the case in PHP. The average amount of time it takes to run the same test of the same 3072 char string with substring() is only 0.005 seconds (or, to drag it out another significant digit, 0.0051 seconds). So it turns out that treating strings like strings when performing these sorts of character-by-character tasks is still preferable to treating the string like an array. |
|
|||||||||||||||||
Search |
|||||||||||||||||||
|
Questions? Comments? Consulting Opportunities? Email matt at aleph-null.tv. This site and all of its content is Copyright © 2003-2005, Aleph-Null, Inc. All rights reserved. |
|||||||||||||||||||