Page 1 of 1

Optimize code (mysqlquery and gdimage)

Posted: Wed Apr 07, 2004 6:27 pm
by Shendemiar
A code to be used a lot. Any hints for optimizing it's performance?

Code: Select all

<?php

#	Includes etc, because this is not INCLUDED but linked!

	$DBC1="x"; $DBC2="x"; $DBC3="x"; $DB="x";
	include ("../../includes/functions/fetch_query.php");

$GameNumber = $_GET['gn'];

$kuva = imagecreate(256, 128);
$bgcolor = ImageColorAllocate($kuva, 255, 255, 255);

$v     = fetch_query("select * from __nations");
while ($row = mysql_fetch_array($v, MYSQL_ASSOC))
	{
	$red = 100;
	$green = 100;
	$blue = 100;

	$fg = $row['n_color'];

	if( eregi( "[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $fg, $ret ) )
	{
		$red = hexdec( $ret[1] );
		$green = hexdec( $ret[2] );
		$blue = hexdec( $ret[3] );
	}
	ImageColorAllocate( $kuva, $red, $green, $blue );
	}

$v     = fetch_query("select * from g_{$GameNumber}_map");
while ($row = mysql_fetch_array($v, MYSQL_ASSOC))
	{
	$xx=$row['x'];
	$yy=$row['y'];
	$va[$xx][$yy] = $row['owner'];
	}

for ($y = 1; $y <= 256; $y++)
	{
for ($x = 1; $x <= 512; $x++)
	{

#if (isset($va[$x][$y]))
#	$var = $va[$x][$y];
#	else
#	$var = 0;

	$var = $va[$x][$y]+1;

imagesetpixel ($kuva, $x/2-1, $y/2-1, $var);

	}
	}

Header("Content-type: image/png");
ImagePng($kuva);
ImageDestroy($kuva);
?>

Posted: Wed Apr 07, 2004 6:47 pm
by TheBentinel.com
Not that it will help alot, but if every tiny iddy-bitty bit counts...

Including a file costs more performance-wise than inline code, so instead of including fetch_query.php, you could duplicate its code here.

Doing a select * fetches all fields, but you might not need them all. It is more efficient to say select field1, field2, etc listing only the fields you want.

It also looks like you store the colors in your database in one format, then pull them out and convert them to some other format. It would be optimal to store them in your database in the same way you intend to use them so you don't have to retranslate the same record over and over.

None of these amount to much individually, and I doubt it'll even be noticeable collectively. But that's what I saw.

Posted: Wed Apr 07, 2004 6:56 pm
by Shendemiar
Good thanks! Did all exept the color storing. Those are mostly for html use... i guess i could have both...

I also noted i'm using 1-512 and 1-256 for input data while the image is only 256*128! I can make it alot faster!

Code: Select all

<?php
while ($row = mysql_fetch_array($v, MYSQL_ASSOC))
	{
	$x=$row['x'];
	$y=$row['y'];
	if (($x % 2 == 0 ) and ($y % 2 == 0))
		{
		$var = $row['owner']+1;
		imagesetpixel ($kuva, $x/2-1, $y/2-1, $var);
		}
	}

?>
Now is there a way to do that any faster? (it's allready better than before)