How to calculate number of lines in PHP

If you search for this topic in a search engine, most of them will tell you that the best way is:

count(explode(“\n”, $line));

But it’s not the most efficient. It’s actually

substr_count($line, “\n”);

On my workstation, running this 500,000 times on a line of 380 lines shows that substr_count executes in 19 seconds whereas count(explode()) combo takes 118 seconds.

Why? Probably because explode() is an additional step in memory usage.

Food for thought.

Related posts:

  1. Weird characters when parsing CSV in PHP
  2. How to setup LAMP stack on Ubuntu VPS
  3. Programmer Day

Leave a Reply

Your email address will not be published. Required fields are marked *

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>