How can PHP be optimized to avoid performance issues when calculating disk space usage, especially for large websites with thousands of files and database entries?

When calculating disk space usage for large websites with thousands of files and database entries, it is important to optimize the PHP code to avoid performance issues. One way to do this is by using efficient algorithms and data structures to minimize the number of iterations and database queries needed to calculate the total disk space.

// Calculate disk space usage for a directory recursively
function calculateDiskSpace($directory) {
    $totalSize = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
        $totalSize += $file->getSize();
    }
    return $totalSize;
}

// Example usage
$directory = '/path/to/directory';
$totalDiskSpace = calculateDiskSpace($directory);
echo "Total disk space usage: " . $totalDiskSpace . " bytes";