Tag Archives: PHP

Performance of yield vs built-in range function

Just out of curiosity, tried to benchmark the memory used by PHP generator(yield) and range function.
Code used here:

function xrange($start, $limit, $step = 1) {
	if ($start < $limit) {
		if ($step <= 0) {
			throw new LogicException('Step must be positive');

		for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } else { if ($step >= 0) {
			throw new LogicException('Step must be negative');

		for ($i = $start; $i >= $limit; $i += $step) {
			yield $i;

$preMemory = memory_get_usage(true);
echo 'Before: ' . $preMemory/1024;

$total = 0;
foreach(xrange(1, 1000000) as $i) {
	$total += $i;

echo "\nYield Took: " . (memory_get_usage(true) - (float)$preMemory)/1024;
$preMemory = memory_get_usage(true);

$total = 0;
foreach(range(1, 1000000) as $i) {
	$total += $i;

echo "\nrange() Took: " . (memory_get_usage(true) - (float)$preMemory)/1024;

Result is (in kilobyte):

Before: 256
Yield Took: 0
range() Took: 768

Increasing the loop 10 times, makes the range() cause stack overflow!


Running/executing PHP from command line

Sometimes we need to check the result of small snippet of code. We can check it easily from command line. I prefer to use the following 2 options:

  1. PsySH: I think its the best REPL for PHP. It has tab completion, documentation and lot of other features. In its site, it says about it: A runtime developer console, interactive debugger and REPL for PHP.
  2. PHP Interactive mode: PHP has an interactive mode, which can be opened running by command #php -a. Command line will show: php > . Then you can run php statements from there
  3. Boris: tiny but useful REPL for PHP. You can find here Boris Installation Guide.

Some useful commands:

  • php -f filename.php -> to run php file
  • php -f filename.php param=value -> to run php file and send query string to script, get using $_GET[‘param’]
  • php -m -> to get all installed modules list
  • php -i -> check php.ini configs. For example you can see the timezone set in config using: php -i | grep timezone
  • php –rf function_name -> quickly check function information