我该如何改进这个PHP代码?

Jas*_*vis 2 php

我有下面的PHP代码,帮助我在脚本中获取照片的缩略图图像路径

这将从mysql DB'2/34/12/thepicture.jpg中获取这样的提供值.然后将它转换为'2/34/12/thepicture_thumb1.jpg'

我相信有更好的表现方式,我愿意接受任何帮助

此外,在一个有50个用户的页面上,这将运行50次以获得50张不同的照片

// the photo has it is pulled from the DB, it has the folders and filename as 1
$photo_url = '2/34/12/thepicture_thumb1.jpg';
//build the full photo filepath
$file = $site_path. 'images/userphoto/' . $photo_url;
// make sure file name is not empty and the file exist 
if ($photo_url != '' && file_exists($file)) {
    //get file info
    $fil_ext1 = pathinfo($file);
    $fil_ext = $fil_ext1['extension'];
    $fil_explode = '.' . $fil_ext;
    $arr = explode($fil_explode, $photo_url);
    // add "_thumb" or else "_thumb1" inbetween 
    // the file name and the file extension 2/45/12/photo.jpg becomes 2/45/12/photo_thumb1.jpg
    $pic1 = $arr[0] . "_thumb" . $fil_explode;
    //make sure the thumbnail image exist
    if (file_exists("images/userphoto/" . $pic1)) {
        //retunr the thumbnail image url
        $img_name = $pic1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我很好奇的一件事是它如何使用pathinfo()来获取文件扩展名,因为扩展名总是3位数,是否有其他方法可以获得更好的性能?

Ima*_*ist 7

这段代码是否存在性能问题,或者您只是过早优化?除非性能严重到足以成为可用性问题,并且分析器告诉您这个代码应该受到责备,否则此代码存在更多紧迫问题.

回答这个问题:"我该如何改进这个PHP代码?" 添加空格.


Dis*_*oat 6

性能方面,如果您调用内置PHP函数,性能非常好,因为您在后台运行已编译的代码.

当然,在你不需要的时候调用所有这些函数并不是一个好主意.在您的情况下,该pathinfo函数返回您需要的各种路径.explode当您可以像这样构建文件名时,可以使用原始名称调用该函数(注意,'filename'仅在PHP 5.2之后可用):

$fInfo = pathinfo($file);
$thumb_name = $fInfo['dirname'] . '/' . $fInfo['filename'] . '_thumb' . $fInfo['extension'];
Run Code Online (Sandbox Code Playgroud)

如果您没有PHP 5.2,那么最简单的方法是忽略该函数并使用strrpossubstr:

// gets the position of the last dot
$lastDot = strrpos($file, '.');
// first bit gets everything before the dot,
// second gets everything from the dot onwards
$thumbName = substr($file, 0, $lastDot) . '_thumb1' . substr($file, $lastDot);
Run Code Online (Sandbox Code Playgroud)