Jump to content

[SOLVED] php loop performance - please tell me a smartest method amoung the two.


jaikar

Recommended Posts

hello there,

 

till now i was using only the classic way of coding. that is mixing the php code with html, now i am trying to separate the php code and html.

 

in a situation, i wanted to pull records from database, and i usually use while($result = mysql_fetch_assoc) then proceed with html. if i separate the php code, and put the "while" in a function that loops the values of the database and returns the array of database values to the html, and i again need to make a second loop using foreach to place the values in the html.

 

so in the later method i am looping twice. is this way recommended ? how far this double looping affect the performance ? which method is the smartest one and the best method ?

 

thankyou!!

Link to comment
Share on other sites

Doing it the first (old) way is definately the most efficient way to do it.  Any code/design separation will ALWAYS add overhead to anything you are doing.  It is really up to you to decide whether or not separating the code (PHP) from the design (HTML) will benefit you in the long run.  If you plan on constantly changing your design, then it may be a good idea.  If the code you're writting is for some thing that you know will never change in appearance, then you don't need to do that.  A lot of people love to use SMARTY templates these days but in my opinion, it is way over-used.  It is used where it is really not needed and therefore just adds extra overhead to everything and makes the site more clunky than it needs to be.

Link to comment
Share on other sites

You don' need to loop twice. You could create HTML in first loop. Later, in HTML page you just should echo created HTML.

Why are you worrying about performance until your page don't have a hundreds of visits per hour. In my opinion much important is time of site development and maintaining easiness.

However Most templating system uses some way of page caching to improve performance.

Link to comment
Share on other sites

You don' need to loop twice. You could create HTML in first loop. Later, in HTML page you just should echo created HTML.

 

The op's entire point is to try and not mix presentation with logic.

How do you think to put array values in HTML without something echo "<td>". $arr[] . "</td>" in a loop except using templating engine or XSLT?

Link to comment
Share on other sites

Well, there is a difference between business logic and presentational logic.

 

Anyway, if you want to prevent looping twice, you can abstract the resource returned by the MySQL functions into a result set object that implements array iteration using SPL's ArrayIterator interface. In that way you can do lazy loading such that the rows are fetched from the database only at the very moment they are going to be used. You can then cache them as an array inside that object as a private property to prevent fetching from the database multiple times if you iterate multiple times.

Link to comment
Share on other sites

thanks guys !!..

 

thorpe is absolutly right... not only mixing presentation with logic, for me mixing is a lot of confusion because, when i use html in php code, i have to decide the css ID, class, etc.. so i jump into css, html... that totally destroy my mood for php coding. moreover.. also i totaly HATE seeing the html code mixed with php !!..

 

dzelenika, you are right that development time is important, and that is my first concern for this question. but also, i am concerned that performance dont go too worse with double looping, i just wanted to know what is the extent of the loss ... whether it is minimal or more ... or do i need to think for any other way... but as you said, caching may help, but only if i use template scripts.. what if i do not use any third party scripts like smarty ?...

 

patrickmvi, mostly it will be large sites like social networking, shopping carts, video sites like youtube.... so changing design may or may not happen, but the major concern is ... as i said before, on reducing the development time, reducing CONFUSIONS!, and also not reducing that much in performance ....

 

Daniel, THANKS MAN !!.. this is something i never ever thought i will get to know !! ... i will look deep into this!! .... also the idea of dzelenika, using XSLT, i never knew XSLT is used for that specific purpose !!....

 

SO... anyhow.. i wanted to KNOW ONE THING FINALLY... is that... IF I use DOUBLE LOOPING for sites like social networking.. where i need to pull lot data from database and with 1000 visits per day, do i need to worry on the performance ?... is the performance drop is worse compared to the performance in avoiding double loop... ?

 

Link to comment
Share on other sites

SO... anyhow.. i wanted to KNOW ONE THING FINALLY... is that... IF I use DOUBLE LOOPING for sites like social networking.. where i need to pull lot data from database and with 1000 visits per day, do i need to worry on the performance ?... is the performance drop is worse compared to the performance in avoiding double loop... ?

 

Unless you pull a lot of rows and get tonnes of hits each day that that page, you won't notice a difference.

Link to comment
Share on other sites

To show you sort of what I mean, here is an example:

 

First a database to test with:

CREATE TABLE `test`.`comments` (
`comment_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) NOT NULL ,
`email` VARCHAR( 255 ) NULL DEFAULT NULL ,
`url` VARCHAR( 255 ) NULL DEFAULT NULL ,
`message` TEXT NOT NULL
) ENGINE = InnoDB;

INSERT INTO `comments` (`comment_id`, `name`, `email`, `url`, `message`) VALUES
(1, 'Daniel', NULL, NULL, 'test'),
(2, 'John Doe', 'jdoe@example.com', 'http://example.com', 'Really cool!!111one!');

 

Next our classes (I pretty quickly stopped bothering to comment):

abstract class Table
{
/**
 * @var PDO
 */
protected $_db;

public function __construct(PDO $db)
{
	$this->_db = $db;
}

protected function _getRowset($query, array $values = array())
{
	$stmt = $this->_db->prepare($query);

	return new Rowset($stmt, $values);
}

/* something more here */
}

class CommentsTable extends Table
{
public function getAll()
{
	return $this->_getRowset('SELECT * FROM comments');
}
}

class Rowset implements SeekableIterator, Countable
{
/**
 * @var PDOStatement
 */
protected $_stmt;

/**
 * @var array
 */
protected $_values = array();

protected $_executed = false;
protected $_count;
protected $_rows = array();
protected $_key = 0;

public function __construct(PDOStatement $stmt, array $values = array())
{
	$this->_stmt = $stmt;
	$this->_values = $values;
}

public function key()
{
	return $this->_key;
}

public function current()
{
	if (!isset($this->_rows[$this->key()])) {
		$this->_rows[$this->key()] = $this->_stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT, $this->key());
	}

	return $this->_rows[$this->key()];
}

public function next()
{
	$this->_key++;

	return $this;
}

public function rewind()
{
	$this->_key = 0;

	return $this;
}

public function seek($position)
{
	if (!$this->exists($position)) {
		throw new OutOfBoundsException('Invalid position.');
	}

	$this->_key = $position;

	return $this;
}

public function count()
{
	$this->_execute();

	if (!isset($this->_count)) {
		$this->_count = $this->_stmt->rowCount();
	}

	return $this->_count;
}

protected function _execute()
{
	if (!$this->_executed) {
		$this->_stmt->execute($this->_values);
		$this->_executed = true;
	}

	return $this;
}

public function exists($position)
{
	return is_int($position) && $position >= 0 && $position < $this->count();
}

public function valid()
{
	return $this->exists($this->key());
}
}

 

And finally we'll get our comments:

$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');

$commentsTable = new CommentsTable($db);
$comments = $commentsTable->getAll();

foreach ($comments as $comment) {
print_r($comment);
}

 

The output should be:

Array
(
    [comment_id] => 1
    [name] => Daniel
    [email] => 
    [url] => 
    [message] => test
)
Array
(
    [comment_id] => 2
    [name] => John Doe
    [email] => jdoe@example.com
    [url] => http://example.com
    [message] => Really cool!!111one!
)

 

 

This is a very simplified example, but it should work as intended.

Link to comment
Share on other sites

I don't understand your question. All methods declared in an interface and all abstract methods in a super class must be implemented, otherwise that class must be abstract. An abstract class needn't have any abstract methods, but it can signify that it's "incomplete" in a way. Maybe see this post?

Link to comment
Share on other sites

 

aww !.. thankyou very much!.... really appreciate for your time in replying...  that post is exactly what i wanted.

 

man !!.. you are awesome .. i am starting to admire your knowledge in php !! ...

 

thanks for all you help !...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.