What is quicker, for camelCase to underscores, preg_replace() or ord()?
My guess is that using ord() will be quicker, since preg_replace() can do much more than needed.
function __autoload($class_name) {
$name = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $class_name));
require_once "some_dir/" . $name . ".php";
}
function __autoload($class_name) {
$class_name[0] = strtolower($class_name[0]);
$len = strlen($class_name);
for ($i = 0; $i < $len; ++$i) {
if (ord($class_name[$i]) > ord('A') && ord($class_name[$i]) < ord('Z')) {
$class_name[$i] = '_' . strtolower($class_name[$i]);
++$len;
++$i;
}
}
return $class_name;
}
Disclaimer
Code examples are taken from Convert CamelCase to under_score_case in php __autoload().
Edit
After jensgram‘s array-suggestion and finding array_splice(), I have come up with the following.
function __autoload ($string) {
$string = str_split($string);
$pos = count($string);
while (--$pos > 0) {
$lower = strtolower($string[$pos]);
if ($string[$pos] === $lower) {
continue;
}
unset($string[$pos]);
array_splice($string, $pos, 0, array('_', $lower));
}
$string = implode('', $string);
return $string;
}
When I will test these methods, I will add this one, but feel free to tell me your results anytime.
i think (and i’m pretty much sure) that the preg_replace method will be faster – but if you want to know, why dont you do a little benchmark calling both functions 100000 times and measure the time?