DJB*_*DJB 6 php arrays performance strpos
我通过Windows身份验证登录用户,然后将该用户的权限存储在会话变量中.我在数据库中使用分隔的权限存储方法,即:
$rights //retrieved from database
= 'read,edit,delete,admin'
Run Code Online (Sandbox Code Playgroud)
所以我的问题应该是我;
//generate variable
$_SESSION['userrights'] = $rights ($rights is retrieved from database)
//use strpos to find if right is allowed
if (strpos($_SESSION['userrights'],"admin") !== false) { // do the function }
Run Code Online (Sandbox Code Playgroud)
要么
//make array of rights
$_SESSION['userrights'] = explode(',',$rights)
//use in_array to find if right is allowed
if (in_array("admin",$_SESSION['userrights'])) { // do the function }
Run Code Online (Sandbox Code Playgroud)
OCD问题的一点,因为我认为差异对于我正在做的事情来说几乎可以忽略不计,但这会更快(使用更少的资源)方法?
除了侮辱我的权利存储方法之外,任何答案都会受到重视!
Jon*_*y 5 13
由于我经常和大型数据集工作,我会一起去isset或!empty关联数组,并检查为重点,像@Barmar建议.以下是基于英特尔®酷睿™i3-540(3.06 GHz)的快速1M基准测试
$test = array("read", "edit", "delete", "admin");
echo "<pre>";
// --- strpos($rights,$test[$i%4]) ---
$rights = 'read,edit,delete,admin';
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (strpos($rights,$test[$i%4]) !== false) { }}
echo ' strpos(... '.round(microtime(true)-$mctime,3)."s\n";
// --- in_array($test[$i%4],$rights) ---
$rights = array("read", "edit", "delete", "admin");
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (in_array($test[$i%4],$rights)) { }}
echo 'in_array(... '.round(microtime(true)-$mctime,3)."s\n";
// --- !empty($rights[$test[$i%4]]) ---
$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (!empty($rights[$test[$i%4]])) { }}
echo ' !empty(... '.round(microtime(true)-$mctime,3)."s\n";
// --- isset($rights[$test[$i%4]]) ---
$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (isset($rights[$test[$i%4]])) { }}
echo ' isset(... '.round(microtime(true)-$mctime,3)."s\n\n";
echo "</pre>";
Run Code Online (Sandbox Code Playgroud)
获胜者是isset:
strpos(... 0.393s
in_array(... 0.519s
!empty(... 0.232s
isset(... 0.209s
Run Code Online (Sandbox Code Playgroud)
strpos是搜索文本针的最快方法,php.net网站:
If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos()....
Run Code Online (Sandbox Code Playgroud)