PHP folder Operation "Copy, delete, view size" Iteration implementation

Source: Internet
Author: User
Tags explode

"Since recursion can be a good solution, why use iterations?" The main reason is also the efficiency problem ...

The concept of recursion is the function call itself, a complex problem decomposed into its similar multiple sub-problems to solve, can greatly reduce the amount of code, making the program look very elegant.

Because the system allocates the run space for each function call and records it using a stack of presses. After the function call is over, the system needs to free up space and bounce the breakpoint back on the stack. So the consumption of recursion is still relatively large.

Even if the language design has been optimized for function call optimization, to ignore recursion caused by the waste of resources, but the depth of recursion will still be limited by the capacity of the system stack, or will throw stackoverflowerror error.

Iterative can be used to make good use of the characteristics of repetitive operation, and theoretically, all recursive functions can be converted to an iterative function, so as far as possible without recursion without recursion, can be replaced by iterative iteration instead.

==================== View folder size =====================

The idea of iteration is to have the computer repeat a set of instructions, and each time the set of instructions is executed, the other new values are introduced from the original values of the variables ... Repeat this process until the end condition is reached or no new value is generated.

Because recursion is equivalent to looping and stacking, you can use the stack for recursion and iterative conversions in iterations.

/** * Folder size * @param $path * @return int*/functionDirsize ($path){    /*Initial conditions*/    $size= 0; $stack=Array(); if(file_exists($path)) {        $path=Realpath($path) . ‘/‘; Array_push($stack, ‘‘); } Else {        return-1; }    /*Iteration Conditions*/     while(Count($stack)!== 0) {        $dir=Array_pop($stack); $handle=Opendir($path.$dir); /*Execution Process*/         while(($item=Readdir($handle)) !==false) {            if($item= = '. ' | |$item= = '.. ')Continue; $_path=$path.$dir.$item; if(Is_file($_path))$size+=filesize($_path); /*Update Condition*/            if(Is_dir($_path))Array_push($stack,$dir.$item. ‘/‘); }        Closedir($handle); }    return $size;}

===================== Copy folder ======================

Iterations and recursion have the four steps of initializing variables, judging the end condition, performing the actual operation, and generating a new variable, except where the position is different.

For example, the initialization of variables, in the iteration is at the beginning of the function, and in recursion refers to the process of other functions passing parameters;

The step of judging the end condition is used in the iteration to determine whether the loop continues, and in recursion to judge the end position of recursion;

Performing the actual operation is a core part of the function in both recursion and iteration, before the new variable step is generated;

The generation of new variables in iterations is the continuation of the iteration, which is the basis of the next recursion in recursion, and the recursive or iterative continuation occurs because of a new variable.

/** * Copy folder * @param $source * @param $dest * @return string*/functionCopydir ($source,$dest){    /*Initial conditions*/    $stack=Array(); $target= ' '; if(file_exists($source)) {        if(!file_exists($dest))mkdir($dest); $source=Realpath($source) . ‘/‘; $dest=Realpath($dest) . ‘/‘; $target=Realpath($dest); Array_push($stack, ‘‘); }    /*Iteration Conditions*/     while(Count($stack)!== 0) {        $dir=Array_pop($stack); $handle=Opendir($source.$dir); if(!file_exists($dest.$dir))mkdir($dest.$dir); /*Execution Process*/         while(($item=Readdir($handle)) !==false) {            if($item= = '. ' | |$item= = '.. ')Continue; $_source=$source.$dir.$item; $_dest=$dest.$dir.$item; if(Is_file($_source))Copy($_source,$_dest); /*Update Condition*/            if(Is_dir($_source))Array_push($stack,$dir.$item. ‘/‘); }        Closedir($handle); }    return $target;}

===================== Delete folder ======================

Aside from language features, the most performance-impacting is redundant code, which is often caused by a lack of design.

In most cases, recursion is more than iterative redundancy code, which is a major factor in low recursive efficiency.

But when the recursive code is concise enough and the redundancy is low enough, the performance of the iteration is not necessarily higher than the recursion.

For example, this iterative implementation of the folder deletion function, the speed is 20% slower than recursion, the main reason is empty folder judgment, in recursion when the folder does not have subfolders, the function will delete all files and the current folder, recursive end.

In an iteration, even if the folder is empty, it needs to be stored on the stack, and the next iteration is judged to be empty before it can be deleted. This is compared to recursive more judgment file is empty, stack, take out iterations and other redundant operations, so processing speed is slower than recursion.

/** * Delete folder * @param $path * @return bool*/functionRmdirs ($path){    /*Initialize Condition*/    $stack=Array(); if(!file_exists($path))return false; $path=Realpath($path) . ‘/‘; Array_push($stack, ‘‘); /*Iteration Conditions*/     while(Count($stack)!== 0) {        $dir=End($stack); $items=Scandir($path.$dir); /*Execution Process*/        if(Count($items) = = = 2) {            rmdir($path.$dir); Array_pop($stack); Continue; }        /*Execution Process*/        foreach($items  as $item) {            if($item= = '. ' | |$item= = '.. ')Continue; $_path=$path.$dir.$item; if(Is_file($_path))unlink($_path); /*Update Condition*/            if(Is_dir($_path))Array_push($stack,$dir.$item. ‘/‘); }    }    return! (file_exists($path));}

==================== View execution Time ======================

This is a function that looks at the execution time (in milliseconds) of the code, executes the target code (or function) through a callback, and finally calculates the execution time (in milliseconds). With this tool you can compare the performance gap between functions, a very simple and practical gadget.

/** * Function execution milliseconds * @param $func * @return int*/functionExec_time ($func){    $start=Explode(‘ ‘,Microtime()); $func();//perform time-consuming operations    $end=Explode(‘ ‘,Microtime()); $sec _time=Floatval($end[0])-Floatval($start[0]); $mic _time=Floatval($end[1])-Floatval($start[1]); return intval(($sec _time+$mic _time) * 1000);}EchoExec_time (function () {    /*time-consuming operations performed*/});

PHP folder Operation "Copy, delete, view size" Iteration implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.