开发者

Reusing the same function and efficiency in php

I have a function that creates an gathers files from a directory and puts them into an array.

function getFiles($folder){
    $ignore = array("index.php",".","..","favicon.gif","favicon.ico",".DS_Store");
    $gottenFiles = array();
        if ($handle = opendir($folder)) {       
            while (false !== ($file = readdir($handle))) {
                if (in_array($file, $ignore)){
                    //do nothing
                }else{
                    array_push($gottenFiles, $file);
                }
            }
        closedir($handle);
        }
    return $gottenFiles;
}

The problem I am trying to wrap my head around is that of efficiency. Everytime I run getFiles("folder"); it runs through the whole process of reassembling the array. I dabbled a bit into static variables and isset conditionals with no progress. Would it be better to call the function inside a variable like this $filesArray = getFiles("folder"); and reuse $filesArray.

Is their a way to set the array once and not continue with opendir?

Are their any modifications I can do to the function 开发者_运维技巧above? (the //do nothing conditional?)

Thanks in advance!


If the value will not be changing much (you aren't adding more files as the script runs) and you are having performance problems, then putting the result in an array is a very good idea.

If your data is changing while you run your script, then you will need to rerun it to get the new information.

However, if you are not seeing performance problems, then this may just be a premature optimization and your time would be better spent elsewhere.

But caching the value in a variable is a simple solution and should solve your problem.


Defining a static variable in a function will made this variable to keep its value accross multiple calls of this function.

So, you can do this :

function getFiles($folder)
{
    static $cache = array();

    if (isset($cache[$folder]))
    {
        return $cache[$folder];
    }

    $ignore = array("index.php",".","..","favicon.gif","favicon.ico",".DS_Store");

    echo "doing the job\n"; // Don't forget to remove

    $gottenFiles = array();
    if ($handle = opendir($folder))
    {
        while (false !== ($file = readdir($handle)))
        {
            if (in_array($file, $ignore))
            {
                //do nothing
            }
            else
            {
                array_push($gottenFiles, $file);
            }
        }

        closedir($handle);
    }

    $cache[$folder] = $gottenFiles;

    return $gottenFiles;
}

If you run this function multiple times on the same folder, the string "doing the job" will show up only the first time. Don't forget to remove the echo statement ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜