Using PHP's file_put_contents function to append, it takes a lot of time to write a file in the loop. Because the File_put_contents function opens the file each time, writes the file, and then closes the file.
Here is the test:
Public function handle ()
{
$TESTTXT = Storage_path (' test.txt ');
for ($i = 0; $i < 100000; $i + +) {
$this->comment (' writing ... ');
File_put_contents ($testTxt, ' Wo shi Tanteng. ') Php_eol, File_append);
}
$this->comment (' Time: '. Round (Microtime (true)-Laravel_start, 2));
}
As shown in the figure:
Takes 165.76 seconds. Now the way to write a file, use the fwrite and lock the same way to cycle the 10w write, the code is as follows:
Public function handle ()
{
$TESTTXT = Storage_path (' test2.txt ');
$handle = fopen ($testTxt, ' WR ');
Flock ($handle, LOCK_EX | LOCK_NB);
for ($i = 0; $i < 100000; $i + +) {
$this->comment (' writing ... ');
Fwrite ($handle, ' Wo shi Tanteng. ') PHP_EOL);
}
Flock ($handle, lock_un);
Fclose ($handle);
$this->comment (' Time: '. Round (Microtime (true)-Laravel_start, 2));
}
Operation Effect as shown:
As shown in the figure, the time consuming 40.46 S has greatly improved the efficiency.
Compared with the file_put_contents function, fwrite improves the efficiency of writing files while using flock to write files and locks to prevent concurrent operation of a file.