gpt4 book ai didi

php - in_array vs strpos 在 php 中的性能

转载 作者:可可西里 更新时间:2023-11-01 13:37:00 26 4
gpt4 key购买 nike

我通过 Windows 身份验证登录用户,然后将该用户的权限存储在 session 变量中。我在数据库中使用分隔的权限存储方法,即:

$rights //retrieved from database 
= 'read,edit,delete,admin'

所以我的问题是我应该;

//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 }

//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 }

有点强制症问题,因为我认为这种差异对于我正在做的事情来说几乎可以忽略不计,但哪种方法更快(使用更少的资源)?

除了侮辱我的权利存储方法的答案外,任何答案都值得赞赏!

最佳答案

因为我经常处理大型数据集,所以我会在关联数组上使用 isset!empty 并检查键,就像@Barmar 建议的那样。这是在 Intel® Core™ 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>";

获胜者是 isset:

  strpos(... 0.393s
in_array(... 0.519s
!empty(... 0.232s
isset(... 0.209s

关于php - in_array vs strpos 在 php 中的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21070691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com