8 jQuery Optimization Tips and Tricks

Its been quite a while since i write anything about jQuery. Furthermore, i have been writing many different optimization articles and jQuery is something that i have not write for quite sometime. Since many uses jQuery quite intensively in either design or application, why don't i give some tips on jQuery too. I think it will be beneficial that such optimization tips can be share and utilize in future application. Therefore, in this article you will see 8 jQuery optimization tips and tricks that might just benefit you during your jQuery coding.

1. Profiling

Once of the most important thing in every optimization, profiling. We can easily perform profiling using firebug. Everyone who is a developer or even designer should be well aware of firebug that could help assist in this task. Profiling allow us to see exactly how many times each function has run and how long does it take. With the help of profiling you will be able to see which function is the bottleneck in your jQuery functions.

2. Benchmarking

Another thing that every optimization will have to come across eventually is benchmarking. In programming, it is very common to use different ways to achieve the same result when we are writing our codes. In order to know which ways give us the best result, benchmarking will be required in order to justify correctly that certain way of achieving the same result is better than the other. Benchmarking across different JavaScript frameworks is the only way we can see which framework run faster than the other in certain ways. Hence, benchmarking is really required in order to justify the efficiency of two or more methods or script.

3. Specific Selector

In jQuery v1.3 below, specific a selector is necessary to optimize jQuery selector speed. A selector that are more specific will result in a faster result found. Hence, an id such as this:

jQuery('#someid').attr('value');

id is always the fastest compare to class or tag where classes is the worst (we do not have document.getElementByClasses don't we). Nonetheless, we can improve the efficiency of the selector by being more specific. Hence, instead of just calling out classes like this:

jQuery('.classes').html();

we can improve it by telling it where it exactly located at

jQuery('div ul li.classes').html();

By being specific in jQuery, we can improve the selector speed. However, this is what happen before jQuery v1.3. After the introduction of 'Sizzling' selector engine, this is no longer the case. We can see that by doing a selector test that the selector has speed up than before. This means that being specific with classes will not have significant differences after v1.3 (because it required more call to be specific) unless you are doing a rather odd selector such as this

jQuery('#id .class div').html();

It will be rather faster with just

jQuery(' .class').html();

Try to avoid id, classes and attribute combination that might just hit your selector badly. The point is to specific a selector but not over specific that might cause a degrade in selector performance.

4. Avoid Unnecessary Selector

Common subexpression elimination is a common way to optimize any programming code. Doing unnecessary selector is expensive. Doing something like this:

jQuery('.class').each(function(){
	jQuery(this).html();
	jQuery(this).find('div').each(function(){
		//etc.
	});
});

which required many selector it is best to use 1 instead since we are repeating ourselves and doing some redundant selector.

jQuery('.class').each(function(){
	var obj = jQuery(this);
	obj.html();
	obj.find('div').each(function(){
		//etc.
	});
});

This is something that we often see in many plugin. Many plugin contains unnecessary selector which degrade the perform of the plugin little by little.

5. Avoid Unnecessary Styling

This is another common mistake that many jQuery developer made. jQuery provides us with the ability to manipulate styling through styling methods. Although it is very convenient to do that but it also contribute to the size of the script and makes maintenance difficult. Furthermore, some of the selector is made solely for styling purposes which makes it even undesirable. To make thing worst, the styles made with jQuery are all inline style which doesn't help caching. Hence, instead of styling everything with jQuery. It is much more advisable to give classes to your tag and style it on a external stylesheet. Instead of writing jQuery styling such as these,

jQuery('div').each(function(){
	var obj = jQuery(this);
	obj.css({'background-color' : 'yellow', 'font-weight' : 'bolder', 'color': '#000', 'font-size': '15px'})
});

Where styling is being applied through jQuery, we can just add a class or even better do it on the HTML file itself!

jQuery('div').each(function(){
	var obj = jQuery(this);
	obj.addClass("mystyling");
});

This way we can easily eliminate a lot of extra code in our script. Unless, absolutely necessary to manipulate styling through jQuery, it is better to leave styling to the stylesheet.

6. Optimize Selector

We can also optimize our selector other than being a bit specific on our selector. The key to optimize our selector is simple. Naive JavaScript provides two method to get id and tag (getElementById and getElementByTagName). Hence, it is always faster to use tag or id on your selector. No matter what algorithm used for classes and attributes selection, the naive built-in JavaScript method will always have the upper hand. Nonetheless, classes and attribute selector have also been improved dramatically through the introduction of 'sizzling' selector engine. However, it is always advisable to reduce the number of attribute selector as they are the slowest in many cases. On the other hand, making your selector as simple as possible is good for pure tag and id selector but may not be true for attribute and selector. Hence,

jQuery('div')
jQuery('#id')
jQuery('.classes')
jQuery('p:last')

is considered as good selectors while the below might not give you very good selector result.

jQuery('body div div')
jQuery('div#id')
jQuery('#id div.classes')
jQuery('.classes p:last')

It is important to treat jQuery as a helper of JavaScript instead of a new language.

7. Avoid DOM Manipulation

Since we are using jQuery as a framework, making life difficult for ourselves is the most silly thing anyone can make. Example, using jQuery to write a table in DOM style~

var table = $('<table></table>');
for (var i = 0; i < 6; i++) {
  var tr = $('<tr></tr>');
  for (var j = 0; j < 7; j++) {
    tr.append('<td></td>');
  }
  table.append($tr);
}

Leaving aside the additional operation on append() each time we call, we are also doing some expensive DOM creation each step when we can really help ourselves by doing a one line query and leave the rest to jQuery. For customize table you might do this.

var table = '<table>'
for (var i = 0; i < 6; i++) {
  var tr = '<tr>';
  for (var j = 0; j < 7; j++) {
    tr +='<td></td>';
  }
  tr +='</tr>';
  table += tr;
}
table += '</table>';
var table = $(table);

For a static table, its really one line.

var table = $('<table><tr><td><td>...</tr><tr>...</tr>...</table>');

But if you really want a table, do it in HTML. You don't need to create everything using jQuery. Treat jQuery as an expensive action and use it when absolute needed. (same goes with styling)

8. Balance between JavaScript and jQuery

jQuery is excellent to speed up ANY front-end developer job. However, there are times when jQuery may take more time to perform certain action than using JavaScript. For example,

	css: function( key, value ) {
		// ignore negative width and height values
		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
			value = undefined;
		return this.attr( key, value, "curCSS" );
	}

The above is a CSS method in jQuery that takes a key and a value which we are familiar using in this way

jQuery('#id').css('display', 'block');

We can see that jQuery present certain overhead for doing something simple where JavaScript can also achieve.

document.getElementById('id').style.display = 'block';

Other methods such as show(), hide(), hasClass() and etc. also present some overhead which you should balance between complexity and efficiency. Hence, we must understand some of the cost of jQuery action and balance between JavaScript and jQuery. jQuery is build for general public and making a general public framework might means additional operation to meet everyone needs. Hence, if you truly going all out on optimization, you should consider the trade-off of some action between JavaScript and jQuery.

Summary

jQuery is a great framework that ease all our development life. Operation that gets complicated can easily become simple with jQuery. However, like i stress the important of keeping out unnecessary jQuery code will certainly help generating a more efficiency and optimize jQuery script.

JavaScript Framework Selector Benchmark Tool

Many front-end developers nowadays are all using javascript framework such as jQuery, Dojo, MooTools, Prototype, etc. Most of us will be wondering which framework is more efficient than the other. Mootools brings us a great tool called Slickspeed to benchmark different framework selector performances against each other. You can even download the source code and test it on your own local drive or server. However, i notice that the result was outdated and a new test should be performed. Ever since jQuery new 'Sizzle' selector engine was released on its version 1.3, many people has been asking how much of a performance it has gain. Furthermore, Resig has been inviting other JavaScript frameworks to implementing Sizzle in its codebase and i was left wondering who did implement Sizzle in its codebase. Out of curiosity, i decided to find out.

Looking at how JavaScript frameworks change as time goes, i think it will be good to have a more dynamic benchmark tool. Therefore, using Slickspeed, i modify the source a little to bring you a more dynamic Slickspeed to benchmark your curiosity.

The tool is fairly easy to use. It is exactly the same as Slickspeed with the additional function of 'add' and 'remove' to benchmark future frameworks. The criteria is simple,

  • 'Add' will required the three textbox to be filled
  • 'Remove' will only required the name to be filled.
  • No name should be the same
  • All path can be take from Google Ajax Framework CDN
  • Function is the symbol used for the framework.

Currently, additional selectors can't be added at the moment but might be in the future so that we can perform benchmark on real selector situation with real document. Below is the updated program but the page must be fully loaded before it is ready to use.

You can also access the full screen version of JavaScript framework selector benchmark tool.

15 Ways to Optimize Your SQL Queries

Previous article was on 10 Ways To Destroy A SQL Database that sort of teaches you what mistakes many company might make on their database that will eventually lead to a database destroy. In this article,  you will get to know 15 ways to optimize your SQL queries. Many ways are common to optimize a query while others are less obvious.

Indexes

Index your column is a common way to optimize your search result. Nonetheless, one must fully understand how does indexing work in each database in order to fully utilize indexes. On the other hand, useless and simply indexing without understanding how it work might just do the opposite.

Symbol Operator

Symbol operator such as >,<,=,!=, etc. are very helpful in our query. We can optimize some of our query with symbol operator provided the column is indexed. For example,

SELECT * FROM TABLE WHERE COLUMN > 16

Now, the above query is not optimized due to the fact that the DBMS will have to look for the value 16 THEN scan forward to value 16 and below. On the other hand, a optimized value will be

SELECT * FROM TABLE WHERE COLUMN >= 15

This way the DBMS might jump straight away to value 15 instead. It's pretty much the same way how we find a value 15 (we scan through and target ONLY 15) compare to a value smaller than 16 (we have to determine whether the value is smaller than 16; additional operation).

Wildcard

In SQL, wildcard is provided for us with '%' symbol. Using wildcard will definitely slow down your query especially for table that are really huge. We can optimize our query with wildcard by doing a postfix wildcard instead of pre or full wildcard.

#Full wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE '%hello%';
#Postfix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE  'hello%';
#Prefix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE  '%hello';

That column must be indexed for such optimize to be applied.

P.S: Doing a full wildcard in a few million records table is equivalence to killing the database.

NOT Operator

Try to avoid NOT operator in SQL. It is much faster to search for an exact match (positive operator) such as using the LIKE, IN, EXIST or = symbol operator instead of a negative operator such as NOT LIKE, NOT IN, NOT EXIST or != symbol. Using a negative operator will cause the search to find every single row to identify that they are ALL not belong or exist within the table. On the other hand, using a positive operator just stop immediately once the result has been found. Imagine you have 1 million record in a table. That's bad.

COUNT VS EXIST

Some of us might use COUNT operator to determine whether a particular data exist

SELECT COLUMN FROM TABLE WHERE COUNT(COLUMN) > 0

Similarly, this is very bad query since count will search for all record exist on the table to determine the numeric value of field 'COLUMN'. The better alternative will be to use the EXIST operator where it will stop once it found the first record. Hence, it exist.

Wildcard VS Substr

Most developer practiced Indexing. Hence, if a particular COLUMN has been indexed, it is best to use wildcard instead of substr.

#BAD
SELECT * FROM TABLE WHERE  substr ( COLUMN, 1, 1 ) = 'value'.

The above will substr every single row in order to seek for the single character 'value'. On the other hand,

#BETTER
SELECT * FROM TABLE WHERE  COLUMN = 'value%'.

Wildcard query will run faster if the above query is searching for all rows that contain 'value' as the first character. Example,

#SEARCH FOR ALL ROWS WITH THE FIRST CHARACTER AS 'E'
SELECT * FROM TABLE WHERE  COLUMN = 'E%'.

Index Unique Column

Some database such as MySQL search better with column that are unique and indexed. Hence, it is best to remember to index those columns that are unique. And if the column is truly unique, declare them as one. However, if that particular column was never used for searching purposes, it gives no reason to index that particular column although it is given unique.

Max and Min Operators

Max and Min operators look for the maximum or minimum value in a column. We can further optimize this by placing a indexing on that particular columnMisleading We can use Max or Min on columns that already established such Indexes. But if that particular column is frequently use, having an index should help speed up such searching and at the same time speed max and min operators. This makes searching for maximum or minimum value faster. Deliberate having an index just to speed up Max and Min is always not advisable. Its like sacrifice the whole forest for a merely a tree.

Data Types

Use the most efficient (smallest) data types possible. It is unnecessary and sometimes dangerous to provide a huge data type when a smaller one will be more than sufficient to optimize your structure. Example, using the smaller integer types if possible to get smaller tables. MEDIUMINT is often a better choice than INT because a MEDIUMINT column uses 25% less space. On the other hand, VARCHAR will be better than longtext to store an email or small details.

Primary Index

The primary column that is used for indexing should be made as short as possible. This makes identification of each row easy and efficient by the DBMS.

String indexing

It is unnecessary to index the whole string when a prefix or postfix of the string can be indexed instead. Especially if the prefix or postfix of the string provides a unique identifier for the string, it is advisable to perform such indexing. Shorter indexes are faster, not only because they require less disk space, but because they also give you more hits in the index cache, and thus fewer disk seeks.

Limit The Result

Another common way of optimizing your query is to minimize the number of row return. If a table have a few billion records and a search query without limitation will just break the database with a simple SQL query such as this.

SELECT * FROM TABLE

Hence, don't be lazy and try to limit the result turn which is both efficient and can help minimize the damage of an SQL injection attack.

SELECT * FROM TABLE WHERE 1 LIMIT 10

Use Default Value

If you are using MySQL, take advantage of the fact that columns have default values. Insert values explicitly only when the value to be inserted differs from the default. This reduces the parsing that MySQL must do and improves the insert speed.

In Subquery

Some of us will use a subquery within the IN operator such as this.

SELECT * FROM TABLE WHERE COLUMN IN (SELECT COLUMN FROM TABLE)

Doing this is very expensive because SQL query will evaluate the outer query first before proceed with the inner query. Instead we can use this instead.

SELECT * FROM TABLE, (SELECT COLUMN FROM TABLE) as dummytable WHERE dummytable.COLUMN = TABLE.COLUMN;

Using dummy table is better than using an IN operator to do a subquery. Alternative, an exist operator is also better.

Utilize Union instead of OR

Indexes lose their speed advantage when using them in OR-situations in MySQL at least. Hence, this will not be useful although indexes is being applied

SELECT * FROM TABLE WHERE COLUMN_A = 'value' OR COLUMN_B = 'value'

On the other hand, using Union such as this will utilize Indexes.

SELECT * FROM TABLE WHERE COLUMN_A = 'value'
UNION
SELECT * FROM TABLE WHERE COLUMN_B = 'value'

Hence, run faster.

Summary

Definitely, these optimization tips doesn't guarantee that your queries won't become your system bottleneck. It will require much more benchmarking and profiling to further optimize your SQL queries. However, the above simple optimization can be utilize by anyone that might just help save some colleague rich bowl while you learn to write good queries. (its either you or your team leader/manager)

10 Ways To Destroy A SQL Database

Database is the asset of most online or internet based company. Everyone looks at how to improve and secure their databases to protect or improve their company. While everyone is searching for remedies or enhancement pills for their company, there are often simple mistakes made by some companies (especially the small to middle ones) that might just destroy their businesses. Rather than looking at how we can protect our database, this article will look at ways to destroy it instead! (through mistake, of course)

Don't Monitor Error Log

The first line of defense that any database would have. Error log may indicates first time problem occurs or warnings that your database might be facing problem. These troubles can be easily avoided or missed depending on what you do. Be my guest and ignore error log will definitely help to destroy your database.

Many company databases are designed in a way to enforce availability. Hence, there will surely be primary and slaves databases in such company. These databases also contain error files. However, if you would like your secondary databases or slave databases go out of sync with the primary database, be sure to ignore the error file and give it some time. Depending on the size of your company, the amount of data lost caused by the lost of synchronization might just cost you dearly when some hero DBA shutdown the primary database without issuing "stop slave" first on the slave database or wait till some errant SQL come down the line. Although this might take some times to destroy your database but its worth to think about using it.

Don't Fine Tune Queries

You have a big server, lots of memory and fast disk, so don't have to worry. Continue with this attitude and you are on your way to success (destroy it!). Developers writing bad code that caused full table scan and trying their best to trash your query cache, overloading your Innodb buffer cache with useless blocks. Plus hitting disk instead of main memory as much as possible? Well, there won't be ANY problem since every piece of hardware is the latest, fastest and most powerful ones! Let's just wait and see till your database fall on its knees! Especially when data is getting larger! That's the best time we see this happen!

Don't Document Procedures and Configurations

Ah! No documentation won't cause a single problem! No problem at all my friend! Why the need to enforce such tedious job when 'we' can maintain the job? Just you wait when the 'we' becomes 'i' and 'i' becomes 'who'. Employees come and go nowadays. People always look for a better future in life and no matter what happens to you, it's really none of their concern. Man! What so difficult? Let's just hire an expert to take the job. Oh boy! That's a great solution! Let's see when he presses the wrong button 🙂

Don't Backup

Another great way to destroy your database is to avoid making backups! Hardware failure is a common thing in data center. Hard disk fail, power supply down, plugs get pulled, basically anything you can imagine. Don't backup regularly can just do the thing!

Its not only hardware that might assist you in your task. Developers or DBA who accidentally deletes data can also be of help. Deleting columns, table, rows, data or even database! These sort of things do happen and it happens quite frequently. Other than deleting data, mistakes made on program might just transfer the wrong data to the wrong place. All of these are just things that might happen to any IT firms. Well, there is always never happen before situation for some of you. Just follow your instinct (backup suck!) on this and you will do just fine.

Don't Use Memory Wisely

Server nowadays have huge memory installed with it. Technology advancement has made everything more powerful than before. Furthermore, it is that affordable that many companies can afford big and fast memory! With such powerful memory backup, we can assure that whatever developers throw in, the server and database will surely be able to take it! We can safely assume MySQL knows our database memory requirement! We just have to run the wizard installation and viola! Everything is automatic nowadays! There won't be such thing as misallocation of memory. The system is perfect.

Good to know. You have everything that required (even attitude) in preparing to bomb up your database.

Don't Worry About Indexes

Indexes is the most effective way to destroy your database. However, you must know the trick to do this. There are two ways to succeed. The first one required you to do absolutely nothing. No indexing is required purely full scan table. However, this required certain criteria to be meet but it should do the trick. If this doesn't suit your taste, you can try a faster way by creating useless or unwanted indexes and ensure that your table have tons of records. This can surely improve the process of destroying your database.

Don't Normalize Your Database Design

If you are just starting to build a system, you can consider skipping normalization in your database design. Skipping normalization can help contribute to bad database design which is part of the plan to destroy a database. Furthermore, without normalization, there is a good chance your system can be inaccurate, slow, and inefficient, and it might not even produce the data you expect.

Don't Make Policies For Database Patch

Its true that majority company doesn't update their databases immediately after a new security vulnerability patch has been released. It would be irresponsible for a company to deploy a patch in production without first running it through quality assurance. Furthermore, some companies didn't event bother to have policies to update their database. If you think that databases are a little more isolated than the desktop, there's less of a security concern and thinks that your databases are more secure because they're behind firewalls and and have a good perimeter security, you are on the right track of destroying a database.

Don't Bother Caching

My database can take tons of crap anything throw towards it. Its the fastest computer (why bother to have technology advancement when we already have the fastest? Dot) on the planet. Cache or no cache won't destroy my database. Its the fastest (ya ya, i get it.). The dramatics performance gain using cache table might not interest you. Scalability, flexibility, availability and performance are just some benefits that caching can gives. Multitier architecture, what bullshit. Your server will NEVER go down and you will NEVER required cache table to be available. Millions of hits on the server database might just do the trick on helping you achieve what you want in this article. It will definitely work better when your table has few millions record and a few lousy queries. (it might not even required millions of hit to kill it)

Don't Use Fast or Reliable Disk

Using something like a single disk or mirror will definitely makes your I/O the main bottleneck on your system. With the help of a single disk, you can expect OS and your database fighting for resources, serving one user at a time while others waiting for their turn. To make things worst, you can try utilize RAID-5 instead of RAID-10. May be you already are!  Well, to  compare between these two, RAID-5 only performed reasonably well on read while RAID-10 exceed almost two times better than RAID-5 on writes. RAID-5 only can handle 1 fails and any drive die will approximately caused 64% degration in read performance until the faulty drive is discovered. Furthermore during recovery, read performance for a RAID5 array is degraded by as much as 80% compared to RAID-5 which only degrade performance on the faulty disk itself. There are more 'advantages' on RAID-5 but i will just stop here. RAID-5 seems to be good with destroying than RAID-10 don't you think so?

Conclusion

The points discuss here might just happen to large data or traffic internet site (well, your site will eventually grow to have big data, hopefully). However, the conclusion to all these jokes are more valuable; Learn to save your ass. No one will.

10 PHP Micro Optimization Tips

There are many ways to improve the way you write your PHP code. And we can easily increase the efficiency of our code just by putting in some effort during development. However, there might be some unknown information that you might not aware in PHP that can help improve your code. In this article, i will try to provide you with some tips that can serve as micro optimization for your code and could also add on to the list of knowledge that you have in PHP. We will also look at many benchmarking of these tips where possible!

Loop

Every program will required certain amount of loop. And loop is considered as efficiency killer if you have many nested loop (means loop in a loop) as one loop will required to run 'n' times and if you have 1 nested loop, this means your program will have to run n2 times. Well, i think you can do the math. But we are not talking about this. There is something more interesting about loop in PHP. There are many ways we can define a loop in PHP. But how do you know which one is the best way to loop your data? Apparently, using a for loop is better than foreach and while loop if the maximum loop is pre-calculated outside the for loop! What do i mean? Basically is this.

#Worst than foreach and while loop
for($i =0; $i < count($array);$i++){
echo 'This is bad, my friend';
}

#Better than foreach and while loop
$total = (int)count($array);
for($i =0; $i < $total;$i++){
echo 'This is great, my friend';
}

The above shows two different ways of writing a for loop. The first way includes the operation count into the loop while the second one pre-calculate the total number of loop outside it. The difference between these two is that the second doesn't run count operation n times while the first one did. You can find this VERY interesting benchmarking on loops on  PHP.

Single Vs Double Quotes

Since i mentioned that benchmarking page on loops, it also includes the benchmark for single(') and double(") quotes. Now, between these two what is the best one to use? It really doesn't makes much differences. But i preferred to use  single(') quote because i don't have to press shift? Just kidding (not). That's one of the reason why i use a single quote over the double one. But the other reason is that PHP will scan through double quote strings for any PHP variables (additional operation) and usually i don't mix my variables and strings into one. I usually use single quote instead. However, you might also have aware that if an empty string is declared using a single quote, it seems like there is a performance pitfall. You or I might want to take note of that. Basically, there is a dollar($) symbols in your string, try to avoid double quote unless its variable?

Pre increment vs Post increment

Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as

$i++;
$++i
$i+=1;
$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn't any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can't really confirm this. Furthermore, it really doesn't makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

Absolute Path VS Relative Path

Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn't. Well, that's the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

Echo Vs Print

Yes! I know, echo is better. But how much better? Interested to know? I am interested. So i went to dig a bit on the internet and found some useful information for benchmarking between these two! Its around 12%-20% faster using echo compare to print when there is no $ symbol in the printing string. And around 40-80% faster if there is an $ symbol used in a printing string! This really demonstrate the differences between the keyword $ symbol used in PHP.

Dot Vs Commas Concatenation

Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a,$b;

Well, between these two which is more efficient? If you did visit the link for benchmarking between echo and print, you might have aware on the exact same test, they also have performed test case for dot and commas. The result shows that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster. On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols.

str_replace vs preg_replace vs ereg_replace

Ok! We have 3 string search function in PHP. Out of these three functions, which do you think will run the fastest? Some of you might have know, str_replace will run faster. Reason? str_replace doesn't run any complex expression unlike preg_replace and ereg_replace. Well, maybe many of you might know that but it is not necessary always str_replace that runs fastest. If you have to call str_replace 5 times compare to preg_replace, which will run faster? (str_replace, of course) Wrong! preg_replace runs 86.99% faster than 5 str_replace function call! Basically, i also have such doubt and search for such benchmark. The benchmark really explains some doubts we have in these functions.

Find Timestamp

When you want to find out the time when your script starts running in order to get that timestamp to store it into your database. The first thing you do is to fire up your Google and search for some PHP function. Well, after PHP5 you do not have to do that. After PHP 5 you can easily retrieve the execution timestamp of your script by using

$_SERVER['REQUEST_TIME']

This could really save some time digging for something that already exist within your reach.

explode Vs preg_split

Well, when you want to split a string what do you use in PHP? I usually used explode because it support even PHP4.0 and that's also what i was taught by my ex-colleagues. The answer in term of efficiency is explode. Split supports regular express and this makes it quite the same comparison between str_replace and preg_replace, anything that have regular expression support will usually be a bit more slower than those that doesn't support it. It took around 20.563% faster using explode in PHP.

Other Benchmarks

I believe this list can go on forever with such great benchmarking site i found. It basically shows you most of the benchmarking between PHP functions or those articles that claim whatever stuff is better than the other in PHP but doesn't provide you with any real evidence on their article. In this article, hopefully i have provided you with the necessary information for you to perform some micro optimization and also other more of such optimization through the benchmarking site.

Summary

I believe many of you have see all these information floating around the internet. But the only differences i see is that they don't really provides you with the real interesting part of this article, that is the benchmark of each test. This article really help me a lot with all the figures and testing given by all these great benchmarking site. Hopefully it also gives you the same result.

P.S: Most of these benchmark sites are run on real-time.