Be a Supporter!

Php: Speed

  • 1,630 Views
  • 3 Replies
New Topic Respond to this Topic
NinoGrounds
NinoGrounds
  • Member since: Nov. 28, 2005
  • Offline.
Forum Stats
Member
Level 19
Programmer
Php: Speed 2006-07-20 12:35:26 Reply

[PHP: Main - Tutoooooorials]

PHP: Speed

Category: Advanced
(because it is assumed that you already know all the functions used here, and some are hard)

Chapter 1 # General Overview / Prologue

As you may not know, PHP is fast, faster than ASP.
PHP4 is faster than ASP for about 200%, but PHP5 is faster even 300%-400%.

This tests have been done by a group of people (including me) on Croatian PHP Site, PHP.hr.

Sometimes you don't have to worry about PHP's speed, like when you are creating some tool for inserting messages.
For instance, a GUESTBOOK. You insert a message once, and user won't mind to wait 0,1 second more because he/she will rarelly insert those messages.

However, if you intergrate loads of features on your site, it can become slow.
For instance, a index.php:

It's a homepage, and if you implement on it news, shoutbox, latest forum posts, notifications, random content, user login screen(which dinamically changes if the user is logged or it is not logged), polls, page generated in and similar it will become really slow.
Plus, you will probably include (or require, which is the same as include, except that it generates an fatal error if it cannot use the file you specified) to retreive those applications.
include() is quite slow. Even its sister-function ,include_once().

Now, I guess you won't go for it and hack the C code of PHP, and so we must find a few ways to make your site FASTER.

Chapter 2 # Communicating between Files
In this situation:
you have a file called news.txt; you store news in it, it doesn't matter if it is via some tool or you do it manually, editting it every time you want to insert some new news.

Example 1 - slower way
<?
$filename = 'news.txt';
include($filename);
?>

The major function here is include().

Example 2 - original way
<?
$filename = 'news.txt';
$open = fopen($filename, "r");
echo fread($open, filesize($filename));
fclose($open);
?>

The major functions here are fopen() for opening the file, then fread() for getting the contents out and fclose() for closing the file connection (aka - to free up the memory which has been taken by this action).

Example 3 - best perfomance
<?
$filename = 'news.txt';
echo file_get_contents($filename);
?>

In this example, with best perfomance, the major function is file_get_contents().
Please Note: file_get_contents() cannot be using for executing *.php files like include() can!

File Writting
Another note I will give you: if you have PHP5, use file_put_contents() instead of fwrite().

In this situation:
you have a file called feedbacks.txt and it is used for storing user's feedbacks.

Example 4 - original way
<?
$filename = 'feedbacks.txt';
$f = fopen($filename, "a+");
fwrite($f, "Good site!");
fclose($f);
?>

The combination of fopen() - fwrite() - fclose().

Example 5 - best way
<?
$filename = 'feedbacks.txt';
file_put_contents($filename, "Good site");
?>

file_put_contents() is a combination of fopen() - fwrite() - fclose().

Chapter 3 # Database Relations (MySQL)
MySQL is good, but it is a bit slow when you need to export for about 200 big news into a document.

Example 1 - fetching all the data
<?
$id = 'some id';
$sql = "SELECT * FROM news WHERE id = $id";
$q = mysql_query($sql);
while ($f = mysql_fetch_assoc($q)) {
echo $f['content'];
}
?>

Seen this now?
We fetched all the data (*), but we needed just the content.
And there was probably more fields, like time data, who posted it and so forth.
That makes the script slower, and it needs more memory from the server, too.

So the better way is:
Example 2 - fetching content, only
<?
$id = 'some id';
$sql = "SELECT content FROM news WHERE id = $id";
$q = mysql_query($sql);
while ($f = mysql_fetch_assoc($q)) {
echo $f['content'];
}
?>

And if you want to fetch something like 'when_posted' too, then you would do so:
Example 3 - fetching more fields
<?
$id = 'some id';
$sql = "SELECT content, time_data FROM news WHERE id = $id";
$q = mysql_query($sql);
while ($f = mysql_fetch_assoc($q)) {
echo $f['content'];
echo "<br /> \n";
echo "Written on {$f['time_data']}. \n";
}
?>

I showed that to show how to fetch multiple fields. Note the coma (,).

Chapter 4 # String Manipulation
Briefly: str_replace() and strpos() are one of the best functions for string manipulation.

str_replace()
Using Regular Expresions (regex) or POSIX-extended (ereg) for simple string manipulation, like replacing some letters with some other letters is not a smart idea while here is str_replace!
str_replace() is a easy function - it doesn't have a power of regex(str_replace( is similar to preg_replace), but it is much less memory intensive, and so it is faster.

strpos()
Sometimes you only want to determine if a particular character(s) exists in a string.
You use strpos() for that!

And yet again, you don't need Regex for that.

Lets make a small example:

Example 1 - find me
<?
$str = "Jesus loved to help"; // i had no other idea..
if (strpos($str, 'Jesus') !== false) {
echo 'A word Jesus got found!";
} else {
echo 'A word Jesus hasn't been found.';
}
?>

Note: use strpos(), not strstr() if you only want to determine if a needle exists in a string, since it is faster.

Final Chapter # It's fucking hot Here
Shit I'm dying in this country!
It's so fucking hot!!
I can't even go the beach, nothing, I am stuck in my room writting Tutorials for PHP: Main.
It is too hot for me even to work on PM Grounds.

Can somebody do something?

WELL WHAT DO YOU THINK ABOUT THIS TUTORIAL ?

-Nino

henke37
henke37
  • Member since: Sep. 10, 2004
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Php: Speed 2006-07-21 07:19:55 Reply

You missed to say that unless changed by a optional parameter you wasn't useing, file_put_contents will do a "w" call, not a "a" call.

Here is some of my tips:
*Get a compile cache, it caches the byte code of each php script and cuts like 30% - 60% of the execution time.
Php code has to be compiled each time and then be run in the zend engine. One cache that is free is Apc(alternative phpcache), find it in pecl(like pear but for c level code).

*Do not use mysql_num_rows if you only need to know the number of rows the query would return, use the count function in the query instead. This avoids all the rows geting read bu the database server who can instead use an optimised function that reads the row count in the table. And since it reads no rows, no rows will need to be sent to the client(php).
<?php
//bad way:
$sql='select * from table';
$rows=mysql_num_rows(mysql_query($sql));

//good way:
$sql='select count(*) from table';
$rows=mysql_result(mysql_query($sql),0,0);
?>


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to Php: Speed 2006-07-21 10:58:19 Reply

I think you could explain how the file_put_contents() function works rather than describing it as the "better" way and a "combination" of the other functions.

I've found the file_(put/get)_contents() functions to be noticable shorter over a period of time using them. While they are much simpler, I don't always use them.

A large issue with file_put_contents() is that it is not available until the PHP5 days. Plenty of servers are still behind the times and have PHP4 installed. You should DEFINITELY mention that. People will be getting an error for calling an undefined function and be scratching their heads.

NinoGrounds
NinoGrounds
  • Member since: Nov. 28, 2005
  • Offline.
Forum Stats
Member
Level 19
Programmer
Response to Php: Speed 2006-07-21 11:55:16 Reply

At 7/21/06 10:58 AM, Pilot-Doofy wrote: A large issue with file_put_contents() is that it is not available until the PHP5 days. Plenty of servers are still behind the times and have PHP4 installed. You should DEFINITELY mention that. People will be getting an error for calling an undefined function and be scratching their heads.

I issued, I forgot to mention this.

And I wanted to mention it!