SplFileObject is faster than fopen/fgets

I had some memory issues recently when reading a file line-by-line with PHP. So I found that SplFileObject is faster and uses less memory than fopen followed by a loop with fgets.

Here is a simple before & after code:

Before

$handle = fopen($path, 'r');
if ($handle) {
    while (($buffer = fgets($handle, 1024)) !== false) {
        // Do something with $buffer ...
    }
    if (!feof($handle)) {
        throw new Exception('Error: unexpected fgets() fail');
    }
    fclose($handle);
}

After

$file = new SplFileObject($path);
while (!$file->eof()) {
    $buffer = $file->current();
    // Do something with $buffer ...
    $file->next();
}

UPDATE
2015/09/08 09:13AM

Maybe you notice an incompatible result when comparing SplFileObject against fopen followed by fgets. So I recommend you to make some tests on your own. Distinctions in server setup and PHP version may lead to different results, for instance.

Advertisements

2 thoughts on “SplFileObject is faster than fopen/fgets

  1. Actually that’s not always true, wy tests showed that fopen()+fgets() is about 20% faster than SplFileObject()+objetc->fgets(). CentOs6 and PHP 5.6

    1. Maybe in some server setups you can get a different result. I was using PHP 5.4 with a real life application, not mock up files, when wrote this post. Anyway, I know this performance matters can be controversial.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s