Skip to content

Commit 5ff390c

Browse files
committed
Tar: write performance optimizations
Tar::addData(): pad only the last block of data and write everything else with just a single writebytes() call and without pack(). Tar::addFile(): move the read chunk size to a class constant.
1 parent f15ef3a commit 5ff390c

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/Tar.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
class Tar extends Archive
1717
{
18+
const READ_CHUNK_SIZE = 1048576; // 1MB
1819

1920
protected $file = '';
2021
protected $comptype = Archive::COMPRESS_AUTO;
@@ -319,8 +320,8 @@ public function addFile($file, $fileinfo = '')
319320
throw new ArchiveIOException('Could not open file for reading: ' . $file);
320321
}
321322
while (!feof($fp)) {
322-
// try to read 1 MB (512 bytes is unperformant)
323-
$data = fread($fp, 1048576);
323+
// for performance reasons read bigger chunks at once
324+
$data = fread($fp, self::READ_CHUNK_SIZE);
324325
if ($data === false) {
325326
break;
326327
}
@@ -375,8 +376,11 @@ public function addData($fileinfo, $data)
375376
$fileinfo->setSize($len);
376377
$this->writeFileHeader($fileinfo);
377378

378-
for ($s = 0; $s < $len; $s += 512) {
379-
$this->writebytes(pack("a512", substr($data, $s, 512)));
379+
// write directly everything but the last block which needs padding
380+
$passLen = ($len >> 9) << 9;
381+
$this->writebytes(substr($data, 0, $passLen));
382+
if ($passLen < $len) {
383+
$this->writebytes(pack("a512", substr($data, $passLen, 512)));
380384
}
381385

382386
if (is_callable($this->callback)) {

0 commit comments

Comments
 (0)