PHP based on iterative implementation of folder copy, delete, view size, etc.

Source: Internet
Author: User
Tags explode
This article mainly introduces PHP based on iterative implementation of folder copy, delete, view size and other operations, simple explanation of the principle of the iteration and combined with the example of PHP to implement the iterative algorithm to achieve the folder copy, delete and view the size of the common operation of the relevant implementation skills, the need for friends can refer to

Specific as follows:

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 */function dirsize ($path) {/  * initial condition */  $size = 0;  $stack = Array ();  if (file_exists ($path)) {    $path = Realpath ($path). '/';    Array_push ($stack, ');  } else {    return-1;  }  /* Iteration Condition *  /while (count ($stack)!== 0) {    $dir = Array_pop ($stack);    $handle = Opendir ($path. $dir);    /* Execute 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 */function copydir ($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 Condition *  /while (count ($stack)!== 0) {    $dir = Array_pop ($stack);    $handle = Opendir ($source. $dir);    if (!file_exists ($dest. $dir)) mkdir ($dest. $dir);    /* Execute 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 a 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 */function rmdirs ($path) {/  * initialization condition */  $stack = Array ();  if (!file_exists ($path)) return false;  $path = Realpath ($path). '/';  Array_push ($stack, ");  /* Iteration Condition *  /while (count ($stack)!== 0) {    $dir = end ($stack);    $items = Scandir ($path. $dir);    /* Execution Process */    if (count ($items) = = 2) {      rmdir ($path. $dir);      Array_pop ($stack);      Continue;    }    /* Execute 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 */function exec_time ($func) {  $start = explode (", microtime ());  $func ();//Perform time-consuming operation  $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);} Echo exec_time (function () {/  * takes a time-consuming operation */});

Related recommendations:

PHP ( iterative + recursive) Implementation of infinite level classification

PHP uses a function static variable to implement a specified number of iterations steps

A detailed explanation of PHP iterators and how to use iterations

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.