【发布时间】:2010-10-22 09:04:20
【问题描述】:
camelCase 下划线更快; 使用 preg_replace() 还是使用 ord() ?
我的猜测是使用 ord 的方法会更快, 因为 preg_replace 可以做的比需要的多。
<?php
function __autoload($class_name){
$name = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $class_name));
require_once("some_dir/".$name.".php");
}
?>
或
<?php
function __autoload($class_name){
// lowercase first letter
$class_name[0] = strtolower($class_name[0]);
$len = strlen($class_name);
for ($i = 0; $i < $len; ++$i) {
// see if we have an uppercase character and replace
if (ord($class_name[$i]) > ord('A') && ord($class_name[$i]) < ord('Z')) {
$class_name[$i] = '_' . strtolower($class_name[$i]);
// increase length of class and position
++$len;
++$i;
}
}
return $class_name;
}
?>
免责声明——取自StackOverflowQuestion 1589468的代码示例。
编辑,在jensgram 的数组建议并找到array_splice 之后,我想出了以下内容:
<?php
function __autoload ($string)// actually, function camel2underscore
{
$string = str_split($string);
$pos = count( $string );
while ( --$pos > 0 )
{
$lower = strtolower( $string[ $pos ] );
if ( $string[ $pos ] === $lower )
{
// assuming most letters will be underscore this should be improvement
continue;
}
unset( $string[ $pos ] );
array_splice( $string , $pos , 0 , array( '_' , $lower ) );
}
$string = implode( '' , $string );
return $string;
}
// $pos could be avoided by using the array key, something i might look into later on.
?>
当我将测试这些方法时,我将添加这个 但请随时告诉我您的结果;p
【问题讨论】:
-
判断什么是更快的最好方法是尝试一下。你有吗?
-
获取您最喜欢的分析器和基准
-
可能对阅读以下内容的人来说很有趣:paulferrett.com/2009/php-camel-case-functionswebdevblog.info/php/…
-
bwah,我会把它放在我的待办事项清单上,这只是一个可以由已经做过这个和/或熟悉分析/基准测试的人来回答的问题。
标签: php function comparison performance