$foo= 'dudes';
$bar= 'whats up';
<?php echo 'hey,'.$foo.' '.$bar.'?'; ?>
<?php echo "hey, $foo $bar?"; ?>
is
<span style="color:#993333">
<?php echo "hey, $foo $bar?"; ?>
</span>
slower than
<span style="color:#339933">
<?php echo 'hey,'.$foo.' '.$bar.'?'; ?>
</span>
?
Yes. It is slightly faster to use single quotes.
This is because when you use double quotes PHP has to parse to check if there are variables in there.
Speed difference in using inline strings vs concatenation in php5?
Nope it is not a bad habit nor slower.
However, when using PHP templating, try to avoid printing several variables at once, to keep things straight.
I'd make it this way:
hey, <?=$foo?> <?=$bar?>?
But it's still matter of style as there are no other reasons to prefer one over another
A note. It's a pity to see numerous answers from not-so-experienced participants, who speaking not from their own real life experience but just repeat some durable rumor, one after another.
Also, I'd say that the question itself has very poor reasoning. If you asks what is slower - you asks wrong question. For the most questions such difference just doesn't matter and just waste of time. Performance tuning is a process, not some "mysterious knowledge". One have to learn how to profile their app and get some basic experience to ask sensible performance related questions. Otherwise there will be no any good.
Yes. It is slightly slower to type constructs with single quotes.
There is no difference in runtime speeds. The only difference is in tokenizing, where single quotes are processed negligibly faster.
I've run a test once (PHP 5.3.2, amd64, linux) to measure some difference, very unscientifically. Single quotes were 14% faster, but only because I pumped 1,000,000,000,000 strings through eval. Otherwise it's hard to measure. And it is seriously irrelevant for real world applications, since you never have that many strings.
Hencewhy the use of single quotes also raises the perception of unintelligent design, when there is another syntax construct that's pretty optimized and way more readable.
Related
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.
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.
I know that using single quotes around a string in PHP is faster than using the double quotes because PHP doesn't need to check for variable presence in the single quoted string. My question is which will perform better:
A) A double quoted string with variables present:
echo "foo bar $baz";
or
B) Single quoted with a concatenated variable:
echo 'foo bar ' . $baz;
I did a benchmark of this on a blog I was working on a while ago. However, as I've come to realize there are a lot of variables. Chief among them are:
How many concatenations are you doing? Each time you do a concatenation PHP re-parses the entire string (or so I've been told). So 1 concatenation may be faster, but 6 may be considerably slower.
Data type. Though I haven't tested this one myself personally I've been told that the data type being concatenated matters as well, though I'm not sure how much.
Over all I'd say it really isn't that big of a deal for you to actually worry about it. Generally speaking it's only going to make a noticeable difference if you're writing a huge site (think MySpace, Facebook, Flickr, etc) and usually by that point you have so much hardware behind you that the single vs double quotes thing becomes irrelevant again.
Personally I'd say there's far more important things that will impact performance in a much more substantial way (caching, sql optimization, auto loading to prevent unnecessary includes, etc).
I personally choose single quotes nearly every time, but not for speed. I do because I think it's more readable. And that to me is important.
In all honesty, I don't think you need to be scrutinizing this particular convention when looking to save performance. But, for what it's worth, I think I recall reading that variables within strings are less-efficient (mind you, it's negligible and in my opinion not an issue) than concatenation.
I wholeheartedly agree with Jonathan Sampson on this issue, but there's a solution which I believe is faster than the ones you posted. Using multiple arguments with echo:
echo 'foo bar', $baz;
This only applies when using the echo statement, in any other context concatenation is probably better, but I strive for readability in this so I use interpolation whenever possible.
I tested with timing (microtime) on my Vista/php5 box with two loops, one for ' and one for ".
On 100 iterations:
- single quotes: 0.000139
- double quotes: 0.000228
On 1000 iterations:
- single quotes: 0.002377
- double quotes: 0.002056
On 2000 iterations:
- single quotes: 0.003562
- double quotes: 0.010041
EDIT:
also timing echo 'Foo', $bar;
100 iterations = 0.000107, 1000 iterations = 0.001381, 2000 iterations = 0.022434.
echo 'Foo', $bar; is the fastest on 100 and 1000 iterations, but for some reason it's slowest on 2000 iterations... ?
Without testing (which is the only proper way to resolve such issues) I'd say single quoted strings with concatenation, because the strings don't have to be parsed. But it's very implementation-dependent.
And double-quoted strings have less visual clutter and cruft. So I'd side with Jonathan in saying that the performance difference is likely not that significant that you should be worried about it; rather, go with the way that is easier to maintain and consistent within your project.
I read an article a while back whereby someone actually tested it.
The conclusion was that single quotes are more efficient, but as the other two answers point out, the performance difference won't be significant enough to worry about.
Here is an older article, last upadted march 2007, but it shows that the performance difference is really low: PHP double versus single quotes by Dave Dash
I recently read another article (can't find it again though), that even stated that there are some circumstances, where double quotes can be faster than single qoutes. Not sure if this is really correct.
So what I would be more concerned about is the readability of your code. If you put the variables inside the quotes it might be harder to read/find if it's a bigger text.
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.
A web site, 5 human years in code (5 developers, approx one year), 10 of thousands of hits every day. Is it really going to have an impact if we change all " to ' where possible?
See the double (") vs. single (') quotes section at PHPBench (scroll to the end of the page). When I invoked the page, I saw the following results:
Single Quotes: 257 µs
Double Quotes: 232 µs
Unless 25µs makes a difference for your problem domain, it doesn't matter.
I'm going to try to work out the math here, someone correct me if I make a mistake. Let's say that you have 10,000 places where you used double quotes instead of single quotes at a 25µs difference per page load (who knows if it actually will work out that way, you need to benchmark your actual code) that would be a would be a 0.25 second difference in execution time. That could be significant depending on server-load if you were Facebook. However, I suspect that there are many other places in your codebase that are far more resource intensive that you will want to optimize before you even look at quotes. Just look at the pain points highlighed on the PhpBench page and you will see that you should have different priorities. Also, these numbers will be drastically different if you run a different php implementation like Quercus - which can solve some performance bottlenecks.
No.
As somebody pointed out in a PHP micro-optimization question a few weeks back (I think the issue was the same ' versus "), implementing the optimization will almost always cost more time than would ever be saved by it.
Yes, you'll end up making that one mistake where you change "$test\n" to '$test\n'.
Real-numbers-wise, no.
The risk of spending time on a micro-optimiztion attempt is that there are probably (yet to be identified) aspects of the code (and any third-party dependencies) which could/should be profiled, then refactored/optimized with a much better efficiency-increase per man-hours-spent ratio.
I can't recommend enough that you read Remember also the rules of Optimization Club.
There is no difference in peformance at run time. But there is a difference at compile time.
The usual way of thinking about quotes in PHP is:
Variables inside single-quoted strings are not parsed, and so the PHP engine doesn't have to waste time looking for them. Hence, single-quoted strings must be more efficient
That assumption is false because the PHP engine doesn't perform that ckeck at run time, but at compile time.
When PHP is parsing your script, if it finds a double-quoted string that has no variables inside it, then that string is treated as a constant string, i.e. its value won't change in the entire script's life-time (if there are variables inside, then it's converted to string concatenations).
Likewise, if PHP finds a single-quoted string, it is treated as a constant as well. But in this case PHP doesn't have to parse the content of the string lookng for variables.
So the answer to your questions depends on whether you are using a PHP caching solution or not (APC, eAcceleator, etc...). If the compilations of your scripts are not being cached then you might have a slight performance improvement because your scripts are compiled every time a visitor loads a page, and hence compilation time is important.
But if the compilations of your scripts are cached, then there is no different on using single- vs double-quoted strings.