Showing posts with label Optimization. Show all posts
Showing posts with label Optimization. Show all posts

Tuesday, February 26, 2008

Caching data

If we are looking for ways to improve our website performance, the cache is the key.

There are many ways to do this, the most common cache is full pages, but sometimes this is not possible. In these cases, the main thing is to locate the slowest processes and try to save their outcome. To that end, the best thing is to use memcache that allows us to keep one variable (serialized, as a string) and recover very quickly.

A more generic solution can be implemented in a class that receives data to store, allowing change the way of doing (memcache, database, files), if necessary to migrate the code to a server that does not have the necessary technology.

Monday, November 5, 2007

States game

Game:

Take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two other U.S. States.

My solution

Any suggestion?

Tuesday, October 30, 2007

Improving Pagination

Recently I discovered a method to improve the performance of a pagination in MySQL. Generally takes two queries to the database, one for bring the data and another to find out how much data is the total. What is new, though not alter the amount of queries, is that we can make the MySQL server has to process only once.

How does this work?
In the first request, in addition to requesting the data, we say to the server to calculate the total number of rows of the query, then we do a query to get this information.

mysql> SELECT * FROM t SQL_CALC_FOUND_ROWS
-> WHERE id> 100 LIMIT 10;
mysql> SELECT FOUND_ROWS ();


This is especially useful if you use an ORDER BY clause, or a complex consultation with subqueries, multiple JOIN or many calculations.

Check MySQL Manual

Tuesday, October 16, 2007

Single and double quoted

For most people, the single and doubles quotes in PHP are equal. But fundamental differences exists. Using double quotes there are more special characters: \n \r \t \\ \$ \" \[0-7] (1,3) \x [0-9A-Fa-f] (1,2) while with single quotes we only have \\ \'.
Knowing this already, we can assume that the single quotes are faster. On the other hand, we must add that within the double quotes variables may be used without concatenate, but writing it directly on the string contents.
More information can be found in the PHP manual, in String section.

Finally, let's compare the times of each, in various circumstances.
View example

Tuesday, September 25, 2007

Conexión por IP

Recently I discovered that is faster to connect to a server used its IP that its name. For example, instead of mysql_connect(“localhost”); one can use mysql_connect(“127.0.0.1”); and it ends up improving the speed of connection. A small optimization, but frequent.

Sunday, September 23, 2007

Storing array elements in a variable

The other day, called the attention to read that is slower to accede to an array element than to a variable. I decided to prove whatever is the difference, and if it is worth the trouble. My conclusion is that the difference exists and if is called more than 10 times to the same index, can be worth the trouble to create a variable for that, but is also only recommendable to do it within a function, in a “scope” so that it is not all along in the memory.

View example

Sunday, September 16, 2007

Iterate over array

Perhaps it sounds repeated to the for - while post, but now instead of executing a code N times, I want to run all the positions of an array. Which is the most advisable way?
In the first place, we have the optimized for.
On the other hand, we can use foreach, that exactly crosses the array of data.
A last alternative is to be crossing the array using its internal pointer.

In this case, the best alternative is foreach, specially dedicated for this.

View example

Tuesday, September 11, 2007

Error reporting

One does not program correctly, if errors exist. And if these errors escape of our sight, it will be more difficult to detect them and to correct them. An error that does not cause negative consequences, continues being an error. Commonest, in this sense, it is to verify the value of variables that are not initialized, or we do not know if they are it… If we proved the difference between

1) if ($variable)
2) if (isset ($variable))
3) if (! empty ($variable))

The first that calls to me attention is the more slow is the first option, if the variable is not defined, but is variable is defined is the more fast that empty and that isset, with which if he is sure that the variable exists, this is the best solution, but before the doubt he is preferable to use empty/isset.

Returning to the subject of the errors, whenever it is codified is good for seeing the errors, therefore always it is good for executing

error_reporting (E_ALL);

while it is being developed, and to reduce the level to E_NONE when he is in a site live, or to eliminate error_display

View example

Sunday, September 9, 2007

Listing directories

The necessity to look for all the archives in a folder is common. The common way is to use opendir, but the function glob approaches to us alongside dark side of the force, offering us a simpler alternative… Nevertheless, this solution is slower.
Another alternative is the function to dir, that returns a directory object, a more “elegant” solution if it is wanted, but is not more than wrapper of the same, reason why it is not faster.

View example

Saturday, September 8, 2007

Avoid double functions calls

I was thinking that I can take any function and optimize it by storing results already calculated in a temporary variable.
Therefore, I took common mathematical formula, the “quadratic one” that is used to obtain the roots of a polynomial of degree two, and began to prove forms to improve it.

Several were the attempts, and the conclusion at which I arrived is that although he is better to store results of calls of functions, is not the best thing to keep it from operating simpler like the multiplication.

View example

Pair or odd

How can we know if an integer number is pair or odd?
Of course, it is not too hard.
When I was just starting, I remembered I have looked for a way to do this, not too practical

floor($a / 2) == $a / 2;

The result is correct, but it can be much easier knowing the % operator

$a % 2 == 0;

However, you can still do it faster, but not necessarily easier, checking if the binary contains the 1 or not.

$a & 1 == 0

View example

str_replace - strtr

This two functions are too similar. Usually, str_replace is more famous, but which one is better? Let's try...

str_replace('e','a','hello world');
strtr('hello world','e','a');

Let's compare a simple replace. In this comparison, str_replace takes a point.

What happens if it is wanted to replace a text that is not?
Both functions are quicker, but str_replace still more optimal. At this instance, it seems this options is better, but both functions allows multiple replacements at a time. Let's try it.

str_replace(array('o','e'),'a','hello world');
strtr('hello world',array('o' => 'a','e' => 'a'));

Here we reeplace "o" and "e" for "a", and str_replace still likes better... Let's give strtr a las chance

str_replace(array('o','e'),array('i','o'),'hello world');
strtr('hello world',array('o' => 'i','e' => 'o'));

In this case, the replacements are 'o' for 'i', and 'e' for 'a', and surprisely strtr takes the victory.

Conclusion: usually, its preferable to use str_replace, but when you want to replace many characters for many others characters (and not only a value) strtr is better.

View example

for - while

Usually, to iterate a code N times you do

for ($a = 0; $a < N; $a++) {

but, thinking a bit, this code can be optimized, because the second and third sentence can be joined, so we get this

for ($a = -1; ++$a < N;) {

Also, you can think it in this way

$a = 0;
while (++$a < N) {

but the previous approach seems (a bit) better, in the practice. This optimization can improve not much your code, we have to keep in mind this is one of the most common iterations, and you can repeat it a lot along your work.

View example