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.

Java Tip : Collections Performance

On Java development, performance is an element that drives developers crazy. Small details can make a considerable difference. Especially when dealing with a big volume of data. One of these details is the kind of collection used to store data. Here it goes some tips on it. Continue reading “Java Tip : Collections Performance”