Software Developer

PHP nl2br() is Slower Than str_replace() to Convert Line Breaks

After running several benchmark tests, I find that the PHP nl2br() is slower than using str_replace() to convert line breaks to HTML tags. This is faster:

str_replace("\n", "<br>", $string)

… which accomplishes the same thing (on non-Windows based servers) as this:

nl2br($string)

Results

nl2br($string) versus str_replace("\n", "<br>", $string)

The average execution times for running 1000 times (in nanoseconds):

Average execution time for test_nl2br():	33,319,351 ns
Average execution time for test_str_replace(): 	18,904,943 ns

 

The average execution times for running 10000 times (in nanoseconds):

Average execution time for test_nl2br():	300,697,963 ns
Average execution time for test_str_replace(): 	185,211,066 ns

Details

I tested it on a 4kb plain text file. The test iterates 1000 times over each function. I repeated this test at least 8 times. Each time, I alternated which function ran first. I took the average of the 8 tests. Then I repeated the same 8 tests but with 10000 iterations each.

This was using PHP version 7.4.11. To run this benchmark test, I used my benchmarking template and the following functions:

function test_nl2br(){
	$file = dirname(__FILE__) . '/test_files/intro.txt';
	$fh = fopen($file, "r");
	$string = fread($fh, filesize($file));
	fclose($fh);
	return nl2br($string);
}
function test_str_replace(){
	$file = dirname(__FILE__) . '/test_files/intro.txt';
	$fh = fopen($file, "r");
	$string = fread($fh, filesize($file));
	fclose($fh);
	return str_replace("\n", "<br>", $string);	
}

See more: ,

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]