Increase loop efficiency

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

Ok, here's what I came up with after looking at your post.

Code: Select all

<?php

$order = array('A' => '', 'K' => 'K', 'Q' => 'Q', 'J' => 'JJJ', 'T' => '', '9' => '', '8' => '', '7' => '', '6' => '', '5' => '', '4' => '', '3' => '3', '2' => '');


# test one
$result = 0;
for($i = 0; $i < 1000; $i++)
{
	$newOrder = '';
	$j = 0;
	$s = microtime(true);
	for($k = 4; $k > 0; $k--)
	{
	    foreach($order as $card)
	    {
		    $j++;
		    if(strlen($card) == $k)
		    {
		        $newOrder .= $card;
		        if(strlen($newOrder)>4)
		        {
		            break(2);
		        }
		    }
	    }
	}
	$e = microtime(true);
		
	$result += ($e - $s);
}


echo '<h3>Double loop</h3>'.substr($newOrder, 0, 5);

echo '<br>';

echo round((($result*1000000)/($i+1))-2, 2).' microseconds<br>Number of loops '.$j.'<br>';


# test two
$result = 0;
for($i = 0; $i < 1000; $i++)
{
	$order;
	$newOrder = '';
	$j = 0;
	$s = microtime(true);
	$quantities = array_map('strlen', $order);
	for($k = 4; $k > 0; $k--)
	{
	    $keys = array_keys($quantities, $k);
	    foreach($keys as $key)
	    {
		    $j++;
		    $newOrder .= $order[$key];
		    if(strlen($newOrder)>4)
		    {
		        break(2);
		    }
		    
		}
    }
	$e = microtime(true);
		
	$result += ($e - $s);
}

echo '<h3>array_map</h3>'.substr($newOrder, 0, 5);

echo '<br>';

echo round((($result*1000000)/($i+1))-2, 2).' microseconds<br>Number of loops '.$j.'<br>';

?>
Both look pretty similar but the output is very different.

Code: Select all

Double loop

JJJKQ
71.66 microseconds
Number of loops 42


array_map

JJJKQ
32.09 microseconds
Number of loops 3
Post Reply