Most expensive operations in PHP? - php

What are some of the most expensive operations in PHP? I know things like overusing the # operator can be expensive. What else would you consider?

serialize() is slow, as is eval(), create_function(), and spawning additional processes via system() and related functions.
beware of anything APC can't cache -- conditional includes, eval()ed code, etc.
Opening database connections. Always cache your connections and re-use them.
Object cloning
Regular expressions. Always use the normal string operations over a regular expression operation if you don't need the functionality of a regexp, e.g. use str_replace() over preg_replace() where possible.
Logging and disk writes can be slow - eliminate unnecessary logging and file operations
Some micro-optimizations that are good practice, but won't make much difference to your bottom line performance:
Using echo is faster than print
Concatenating variables is faster than using them inline in a double-quoted string.
Using echo with a list of arguments is faster than concatenating the arguments. Example: echo 'How are you ',$name,' I am fine ',$var1 is faster than echo 'How are you '.$name.' I am fine '.$var1
Develop with Notices and Warnings turned on. Making sure they don't get triggered saves PHP from having to run error control on them.

Rather than trying to figure out potential areas that are slow, use a profiling tool. Installing xDebug was probably one of the easiest and best things I've done to improve the code I write. Install with WinCacheGrind (or the correct version for your OS) for best results.

"Hello $name"
syntax is slower than
'Hello ' . $name
also __get() __set() __call(), etc are slow
and, if you care so much, you can use optimized structures from SPL

Anything that's going though a network connection -- like calling a webservice, for instance : it'll generally take more time than doing an operation locally.
(Even if it doesn't cost much CPU, it'll cost time)

I'd say SQL queries inside loops. Such as this:
foreach ($db->query('SELECT * FROM categories') as $cat)
{
foreach ($db->query('SELECT * FROM items WHERE cat_id = ' . $cat['cat_id']) as $item)
{
}
}
Which, for the record, could be shortened into something like this:
$sql = 'SELECT c.*, i.*
FROM categoriess c
LEFT JOIN items i USING (cat_id)
ORDER BY c.cat_order';
foreach ($db->query($sql) as $row)
{
}

curl_exec() is very slow, compared to typical operations. Also, most str_* operations are faster than regex operations.

json_encode is faster than serialize
Concatenate in loop is faster than implode
People think that # is expensive maybe only because this saying is quite wide-spread on the web.
quoting from : http://www.php.net/manual/en/language.operators.errorcontrol.php#102543
If you're wondering what the performance impact of using the #
operator is, consider this example. Here, the second script (using
the # operator) takes 1.75x as long to execute...almost double the
time of the first script.
So while yes, there is some overhead, per iteration, we see that the #
operator added only .005 ms per call. Not reason enough, imho, to
avoid using the # operator.
real 0m7.617s user 0m6.788s sys 0m0.792s
vs
real 0m13.333s user 0m12.437s sys 0m0.836s
You can nearly unable to "overuse" an operator and it often worth if it is doing an operation you want.

foreach() statements, especially with nesting, are frequently expensive; though that's as much my naive -and occasionally poorly-planned- approach to programming as php's fault.
Though I think it's true, also, of JS and other languages, so almost certainly my fault. =/

From my own experience the most expensive operation in real terms is the echo statement. Try and join all string together before outputting them to the browser, followed by database calls especially joins!
Code can also sometimes get a x10 performance increase by just simply refactoring your algorithms and data structures. Get any program and try to half its length, can you half it again?

uniqid() is stupid expensive. Don't use to generate lots of unique identifiers.

Related

Does extensive use of php echo statement make page load times slower?

I know this question has been asked before but I haven't been able to find a definitive answer.
Does the overly use of the echo statement slow down end user load times?
By having more echo statements in the file the file size increases so I know this would be a factor. Correct me if I'm wrong.
I know after some research that using php's ob_start() function along with upping Apaches SendBufferSize can help decrease load times, but from what I understand this is more of decrease in php execution time by allowing php to finish/exit sooner, which in turn allows Apache to exit sooner.
With that being said, php does exit sooner, but does that mean php actually took less time to execute and in turn speed things up on the end user side ?
To be clear, what I mean by this is if I had 2 files, same content, and one made use of the echo statement for every html tag and the other file used the standard method of breaking in and out of php, aside for the difference in file size from the "overly" use of the echo statement (within reason I'm guessing?), which one would be faster? Or would there really not be any difference?
Maybe I'm going about this or looking at this wrong?
Edit: I have done a bit of checking around and found a way to create a stop watch to check execution time of a script and seems to work quit well. If anybody is interested in doing the same here is the link to the method I have chosen to use for now.
http://www.phpjabbers.com/measuring-php-page-load-time-php17.html
Does the overly use of the echo statement slow down end user load times?
No.
By having more echo statements in the file the file size increases so I know this would be a factor. Correct me if I'm wrong.
You are wrong.
does that mean php actually took less time to execute and in turn speed things up on the end user side?
No.
Or would there really not be any difference?
Yes.
Maybe I'm going about this or looking at this wrong?
Definitely.
There is a common problem with performance related questions.
Most of them coming up not from the real needs but out of imagination.
While one have to solve only real problems, not imaginable ones.
This is not an issue.
You are overthinking things.
This is an old question, but the problem with the logic presented here is it assumes that “More commands equals slower performance…” when—in terms of modern programming and modern systems—this is an utterly irrelevant issue. These concerns are only of concerns of someone who—for some reason—programs at an extremely low level in something like assembler and such,.
The reason why is there might be a slowdown… But nothing anyone would ever humanly be able to perceive. Such as a slowdown of such a small fraction of a second that the any effort you make to optimize that code would not result in anything worth anything.
That said, speed and performance should always be a concern when programming, but not in terms of how many of a command you use.
As someone who uses PHP with echo statements, I would recommend that you organize your code for readability. A pile of echo statements is simply hard to read and edit. Depending on your needs you should concatenate the contents of those echo statements into a string that you then echo later on.
Or—a nice technique I use—is to create an array of values I need to echo and then run echo implode('', $some_array); instead.
The benefit of an array over string concatenation is it’s naturally easier to understand that some_array[] = 'Hello!'; will be a new addition to that array where something like $some_string .= 'Hello!'; might seem simple but it might be confusing to debug when you have tons of concatenation happening.
But at the end of the day, clean code that is easy to read is more important to all involved than shaving fractions of a second off of a process. If you are a modern programmer, program with an eye towards readability as a first draft and then—if necessary—think about optimizing that code.
Do not worry about having 10 or 100 calls to echo. When optimizing these shouldn't be even take in consideration.
Think that on a normal server you can run an echo simple call faster than 1/100,000 part of a second.
Always worry about code readability and maintenance than those X extra echo calls.
Didn't made any benchmark. All I can say is, in fact when your echo strings (HTML or not) and use double quotes (") it's slower than single quotes (').
For strings with double quotes PHP has to parse those strings. You could know the possibility to get variables inside of strings by just insert them into your string:
echo "you're $age years old!";
PHP has to parse your string to lookup those variables and automatically replace them. When you're sure, you don't have any variables inside your string use single quotes.
Hope this would help you.
Even when you use a bunch of echo calls, I don't think it would slow down your loading time. Loading time depends on reaction time of your server and execution time. When your loading time would be to high for the given task, check the whole code not only the possibility of echoes could slow down your server. I think there would be something wrong inside your code.

PHP coding convention and efficiency

Consider
<?php echo $name;?>
and compare with
<?php echo "{$name}";?>
then consider hundreds of these in different variations on the same page.
Does one or the other convention affect
performance in any way or is it just a matter of preference?
This question has been addressed quite well before: Opening/closing tags & performance?
In brief, here is the answer:
3 simple rules for you to get it right:
- No syntax issue can affect performance. Data manipulation does.
- Speak of performance only backed with results of profiling.
- Premature optimization is the root of all evil
It may affect the performance, but that should never be the point to influence how you write good and readable code. The difference is negligible.
Just my 2 cent: The first one is much more readable, if I have huge parts of html and I just want to integrate some variables. The second one is more readable, if its only a single line or something.
The single quotes (') is more faster than double quotes ("), because the parser don't try to find variables in the string.
So, I think that the first script is the best way.
The first example will be slightly faster because using PHP to echo content adds a tiny latency over just displaying text using raw html.
However, this difference is not noticeable at all and I would advise you to use choose whichever you prefer.
Some conventions can possibly effect performance if they are calling different functions or if they take up more space (so the script physically takes up more space in memory) - but this is completely negligible and just a matter of preference. If you compare it to something like Smarty or another Templating system - that on the other hand will effect performance.

PHP efficiency question

I am working on website and I am trying to make it fast as much as possible - especially the small things that can make my site a little bit quicker.
So, my to my question - I got loop that run 5 times and in each time it echo something, If I'll make variable and the loop will add the text I want to echo into the variable and just in the end I'll echo the variable - will it be faster?
loop 1 (with the echo inside the loop)
for ($i = 0;$i < 5;$i++)
{
echo "test";
}
loop 2 (with the echo outside [when the loop finish])
$echostr = "";
for ($i = 0;$i < 5;$i++)
{
$echostr .= "test";
}
echo $echostr;
I know that loop 2 will increase a bit the file size and therfore the user will have to download more bytes but If I got huge loop will it be better to use second loop or not?
Thanks.
The difference is negligible. Do whatever is more readable (which in this case is definitely the first case). The first approach is not a "naive" approach so there will be no major performance difference (it may actually be faster, I'm not sure). The first approach will also use less memory. Also, in many languages (not sure about PHP), appending to strings is expensive, and therefore so is concatenation (because you have to seek to the end of the string, reallocate memory, etc.).
Moreover, file size does not matter because PHP is entirely server-side -- the user never has to download your script (in fact, it would be scary if they did/could). These types of things may matter in Javascript but not in PHP.
Long story short -- don't write code constantly trying to make micro-optimizations like this. Write the code in the style that is most readable and idiomatic, test to see if performance is good, and if performance is bad then profile and rewrite the sections that perform poorly.
I'll end on a quote:
"premature emphasis on efficiency is a big mistake which may well be the source of most programming complexity and grief."
- Donald Knuth
This is a classic case of premature optimization. The performance difference is negligible.
I'd say that in general you're better off constructing a string and echoing it at the end, but because it leads to cleaner code (side effects are bad, mkay?) not because of performance.
If you optimize like this, from the ground up, you're at risk of obfuscating your code for no perceptable benefit. If you really want your script to be as fast as possible then profile it to find out where the real bottlenecks are.
Someone else mentioned that using string concatenation instead of an immediate echo will use more memory. This isn't true unless the size of the string exceeds the size of output buffer. In any case to actually echo immediately you'd need to call flush() (perhaps preceded by ob_flush()) which adds the overhead of a function call*. The web server may still keep its own buffer which would thwart this anyway.
If you're spending a lot of time on each iteration of the loop then it may make sense to echo and flush early so the user isn't kept waiting for the next iteration, but that would be an entirely different question.
Also, the size of the PHP file has no effect on the user - it may take marginally longer to parse but that would be negated by using an opcode cache like APC anyway.
To sum up, while it may be marginally faster to echo each iteration, depending on circumstance, it makes the code harder to maintain (think Wordpress) and it's most likely that your time for optimization would be better spent elsewhere.
* If you're genuinely worried about this level of optimization then a function call isn't to be sniffed at. Flushing in pieces also implies extra protocol overhead.
The size of your PHP file does not increase the size of the download by the user. The output of the PHP file is all that matters to the user.
Generally, you want to do the first option: echo as soon as you have the data. Assuming you are not using output buffering, this means that the user can stream the data while your PHP script is still executing.
The user does not download the PHP file, but only its output, so the second loop has no effect on the user's download size.
It's best not to worry about small optimizations, but instead focus on quickly delivering working software. However, if you want to improve the performance of your site, Yahoo! has done some excellent research: developer.yahoo.com/performance/rules.html
The code you identify as "loop 2" wouldn't be any larger of a file size for users to download. String concatination is faster than calling a function like echo so I'd go with loop 2. For only 5 iterations of a loop I don't think it really matters all that much.
Overall, there are a lot of other areas to focus on such as compiling PHP instead of running it as a scripted language.
http://phplens.com/lens/php-book/optimizing-debugging-php.php
Your first example would, in theory, be fastest. Because your provided code is so extremely simplistic, I doubt any performance increase over your second example would be noticed or even useful.
In your first example the only variable PHP needs to initialize and utilize is $i.
In your second example PHP must first create an empty string variable. Then create the loop and its variable, $i. Then append the text to $echostr and then finally echo $echostr.

PHP ideas specialization for performance

What kind of ideas or tips and tricks do you have in order to boost PHP performance.
Something like,
I use:
$str = 'my string';
if(isset($str[3])
Instead of:
if(strlen($str) > 3)
Which is a bit faster.
Or storing values as keys instead of vars in array, makes searching if key exists much faster. Hence using isset($arr[$key]) instead of array_exists($arr, $key)
Shoot your ideas, i would love to hear them.
Use a profiler and measure your performance.
Optimise the areas that need it.
Typical areas that will give you the most bang for effort in a typical php website.
think about database queries carefully. They often take up most of the execution time.
Don't include code you don't need
Don't write you own versions of the built in functions - the built in ones are compiled C and will be faster that you L33T php version.
Use an OpCode cache.
Most PHP accelerators work by caching the compiled bytecode of PHP scripts to avoid the overhead of parsing and compiling source code on each request (some or all of which may never even be executed). To further improve performance, the cached code is stored in shared memory and directly executed from there, minimizing the amount of slow disk reads and memory copying at runtime.
Dont do as list of this things, you'll make your code unreadable... or harder to read, even by yourself.
Leave this things to the Zend Engine, or to the accelerator of your choice( actually a opcode cache).
Optimizations like these may be faster now, but they may actually get slower if the guys from the zend engine starts to auto-optimize things like these.
Ex: one may speed up the strlen() function a lot by giving up on z-strings and using l-strings(the length being in the first char, or word). This in turn will end up making your (pre-optimized) script slower if you optimize like this.
Use parameterized SQL instead of mysql_query(). And reduce the overall number of database queries. Everything else are shallow optimizations.

PHP array vs PHP Constant?

I am curious, is there any performance gain, like using less memory or resources in PHP for:
50 different setting variables saved into array like this
$config['facebook_api_secret'] = 'value here';
Or 50 different setting variables saved into a Constant like this
define('facebook_api_secret', 'value here');
I think this is in the realm of being a micro-optimization. That is, the difference is small enough that it isn't worth using one solution over the other for the sake of performance. If performance were that critical to your app, you wouldn't be using PHP! :-)
Use whatever is more convenient or that makes more sense. I put config data into constants if only because they shouldn't be allowed to change after the config file is loaded, and that's what constants are for.
In my informal tests, I've actually found that accessing/defining constants is a bit slower than normal variables/arrays.
it's not going to make a different anyway; more than likely whatever you do with these will happen in thousandths of a second.
Optimizing your DB (indexing, using EXPLAIN to check your queries) and server set up (using APC) will make more a difference in the long run.
Performance gains for 50 variables using a different coding technique / clever programming tricks is the wrong way to do things in PHP. Always remember: the optimizer is smarter than you are.
You will not receive any kind of performance gain for either of these. The real question is which one is more useful.
For scalar values (Strings, ints, etc) that are defined once, should never change, and need to be accessible all over the place, you should use a constant.
If you have some kind of complex nested configuration, eg:
$config->facebook->apikey = 'secret_key';
$config->facebook->url = 'http://www.facebook.com';
You may want to use an array or a configuration api provided by one of the many frameworks out there (Zend_Config isn't bad)

Categories