如果文件在 PHP 中不存在,则使用 is_file 或 file_exists 时响应缓慢

问题描述 投票:0回答:0

我有一段代码将 JSON 文件加载到数组中,我最近注意到这个脚本运行缓慢。

我所做的是首先测试文件是否存在(我同时使用了 file_exists 和 is_file)。如果文件存在,处理时间非常快(例如 0.00054097175598145 秒),但奇怪的是,如果文件不存在,因此例程没有运行,它需要一秒钟(2.7179718017578E-5)。我的猜测是它在返回文件未找到之前检查整个目录,但是目录中只有 700 个文件所以我仍然不希望它需要 2 秒

    $start = microtime(true);
    $user = $row['id'];
    echo "User " . $user . '<br>';
    $leaguelist = array();
    if (is_file("../leagues/leagues/" . $user . ".txt")) 
    {
        $leagues = file_get_contents("../leagues/leagues/" . $user . ".txt");
        $leaguelist2 = json_decode($leagues, true);
        foreach ($leaguelist2 as $indileagues) {
            $leaguelist[] = $indileagues[0];
        }
    }
$time_elapsed_secs = microtime(true) - $start;

我真的需要这段代码更快,有没有更快的方法来检查文件是否存在?

php file file-exists
© www.soinside.com 2019 - 2024. All rights reserved.