In PHP, why is echo faster than print?
They do the same thing... Why is one faster than the other?
Do they do exactly the same thing?
echo and print are virtually (not technically) the same thing. The (pretty much only) difference between the two is that print will return the integer 1, whereas echo returns nothing. Keep in mind that neither is actually a function, but rather language constructs. echo allows you to pass multiple strings when using it as if it were a function (e.g., echo($var1, $var2, $var3)).
echo can also be shorthanded by using the syntax <?= $var1; ?> (in place of <?php echo $var1; ?>).
As far as which is faster, there are many online resources that attempt to answer that question. PHP Benchmark concludes that "[i]n reality the echo and print functions serve the exact purpose and therefore in the backend the exact same code applies. The one small thing to notice is that when using a comma to separate items whilst using the echo function, items run slightly faster."
It will really come down to your preference, since the differences in speed (whatever they actually are) are negligible.
Print always returns 1, which is also probably why it's slower
Print has a return value, this is the only difference.
The speed difference (if any) is so miniscule that it's not worth the effort thinking about micro optimisations like this, and it's absolutely not worth updating any old code to switch prints to echos. There are much better ways to speed up your site, if this is your goal.
As my experience and knowledge, You are wrong. print is faster than echo in the loops autobahn and hypertexts.
Which is faster?
I'm implementing a test that shows the difference between print and echo.
$start = microtime(1);
for($i = 0; $i < 100000; $i++)
echo "Hello world!";
echo "echo time: " . round(microtime(1) - $start, 5);
$start = microtime(1);
for($i = 0; $i < 100000; $i++)
print "Hello world!";
echo "print time: " . round(microtime(1) - $start, 5);
result:
echo time: .09
print time: .04
Another reference is phpbench that shows this fact.
Comparision
Now its time to investigate that why print is faster than echo. When you are using loops, of course, php checks if echo has multiple values to print or not, but always print can take only one parameter and it's not needed to be checked in loops. also when there are multiple values for echo bad things come through, like converting them to string and streaming them, I do believe that in huge hypertexts these problem come through too because you are forcing php to process before printing. But in small jobs like printing, only a small string echo I good (if you consider concatenations) because it doesn't return anything like print.
Related
Let's say I have $variable holding more than 500 kb info.
while ($row = mysqli_fetch_assoc($selectFromTable))
{
$variable .= "<p>$row[info]</p>";
}
or
while ($row = mysqli_fetch_assoc($selectFromTable))
{
echo "<p>$row[info]</p>";
}
Optimization wise, is it better to echo the info right away than saving it to a variable?
I can't decide because I can't see the difference in performance because I don't know what tool to use in monitoring the response time. Any suggestion?
Even though there is not enough difference in performance, I still wanted to learn on how can I optimize my coding.
There is no significant difference in speed or memory usage between the two pieces of code you listed. They both build a new string that contains the value of $row['info'] enclosed in a <p> HTML element.
You can pass each string as an individual argument to echo:
echo "<p>", $row['info'], "</p>";
This avoids the creation of a new string, uses less memory and runs slightly faster (the improvement speed is not significant unless you do it thousands of times in a loop).
Read about the echo language construct.
Also please note that $row[info] is not correct. The correct way is $row['info']. It is explained in the documentation why.
You need to do something with variable, instead of just saving some data in it in the first loop.
With your current setup first loop with only variable storage will always be faster as operation with IO (input/output) devices are slow that means echo to print output in screen.
But if you add an echo after the variable statement then, loop with only single echo will obviously be faster.
I'm coding a multi language website. The text for each page is loaded from a MySQL database and should be assigned to an array or constant to insert it into the web content.
I would like to know if it is better, to save memory and for best performance, the use of constants or arrays to store the text. i.e.
foreach ($db_text_object as $t){
$text["$t->key"] = $t->text;
}
or:
foreach ($db_text_object as $t){
define($t->key, $t->text);
}
To be used as:
echo $text['mytext'];
or:
echo mytext;
Any other comment about advantage or disadvantage of each method will be appreciated.
Thank you.
I don't think either will have a significant impact on performance, especially since the bottleneck will be getting all the data from the database every single time. If you're really interested in whether it makes a difference: try it both ways and measure it.
When you're done doing that, do it right by using a native extension like gettext, which was made for this exact purpose, does internal caching of binary translation files and comes with a whole ecosystem of tools supporting the translation workflow.
The performance difference will be too trivial or too minute
I personally go with the arrays, since you would be able to access it in a simpler way..
Benchmarking results...
<?php
$db_text_object=[1,2,3,4,5];
$start = microtime(true);
foreach ($db_text_object as $k=>$v){
$text[$k] = $v;
}
echo "Constant Performance: " . (microtime(true) - $start) . "\n";
$start = microtime(true);
foreach ($db_text_object as $k=>$v){
define($k, $v);
}
echo "Array Performance: " . (microtime(true) - $start) . "\n";
OUTPUT:
Constant Performance: 1.9073486328125E-5
Array Performance: 1.3113021850586E-5
Benchmarking Demo at CodeViper
Perhaps this is a petty question, but consider the following PHP code:
$a = "foo1"; $b = "foo2"; $c = "foo3";
echo $a, $b, $c;
echo $a . $b . $c;
echo "$a$b$c";
aren't these three statements equivalent. What's the difference.
What if one cannot decide whether to use one or the other?
The first one simply echoes out 3 values in a single call. The other two do string concatenations and output the result of that operation. In other words, if you were doing this a few zillion times in a row, the first version would probably be slightly faster, because there's less string operations going on.
That being said, even if you reduce string operations in PHP, the output produced by the echo statements will still be tacked onto the end of an output buffer, and stuffing in a single larger string may be more efficient than multiple smaller strings.
In the grand scheme of things, there'll probably be very little difference between any of those versions, so go with the one that makes the most sense to you, and is easiest for maintenance down the road.
They are mostly equivalent, I would assume that the only real difference would be on performance of how it executes. This may become insignificant or nonexistent if you use a php optimizer.
If I was to guess, I would say that echo #1 is fastest, followed by echo #2, and lastly echo #3.
Why I say this?:
echo #1:
plays directly off of the language construct that it is and simply spits out the variables.
echo #2:
must first concat the strings together and then echo it out
echo #3:
Must first search through the string and replace what it finds with what the variable is. Which would most likely be the most expensive operaion to handle.
Additional note:
You should ALWAYS use single quotes when putting strings into variables unless you explicitly want variables replaced on the inside. Thus your first line:
$a = "foo1"; $b = "foo2"; $c = "foo3";
Should be:
$a = 'foo1'; $b = 'foo2'; $c = 'foo3';
Just a note about the third method:
When using variables in double quotes, I am in the habit of using curly brackets because they escape array-based variables:
echo "{$a}{$b}{$c}";
If $c were an associative array and you wanted to output some element of it, the statement would then be:
echo "{$a}{$b}{$c['foo']}";
Sometimes this results in neater string formatting than concatenating variables and strings together for output.
I use often the function sizeof($var) on my web application, and I'd like to know if is better (in resources term) store this value in a new variable and use this one, or if it's better call/use every time that function; or maybe is indifferent :)
TLDR: it's better to set a variable, calling sizeof() only once. (IMO)
I ran some tests on the looping aspect of this small array:
$myArray = array("bill", "dave", "alex", "tom", "fred", "smith", "etc", "etc", "etc");
// A)
for($i=0; $i<10000; $i++) {
echo sizeof($myArray);
}
// B)
$sizeof = sizeof($myArray);
for($i=0; $i<10000; $i++) {
echo $sizeof;
}
With an array of 9 items:
A) took 0.0085 seconds
B) took 0.0049 seconds
With a array of 180 items:
A) took 0.0078 seconds
B) took 0.0043 seconds
With a array of 3600 items:
A) took 0.5-0.6 seconds
B) took 0.35-0.5 seconds
Although there isn't much of a difference, you can see that as the array grows, the difference becomes more and more. I think this has made me re-think my opinion, and say that from now on, I'll be setting the variable pre-loop.
Storing a PHP integer takes 68 bytes of memory. This is a small enough amount, that I think I'd rather worry about processing time than memory space.
In general, it is preferable to assign the result of a function you are likely to repeat to a variable.
In the example you suggested, the difference in processing code produced by this approach and the alternative (repeatedly calling the function) would be insignificant. However, where the function in question is more complex it would be better to avoid executing it repeatedly.
For example:
for($i=0; $i<10000; $i++) {
echo date('Y-m-d');
}
Executes in 0.225273 seconds on my server, while:
$date = date('Y-m-d');
for($i=0; $i<10000; $i++) {
echo $date;
}
executes in 0.134742 seconds. I know these snippets aren't quite equivalent, but you get the idea. Over many page loads by many users over many months or years, even a difference of this size can be significant. If we were to use some complex function, serious scalability issues could be introduced.
A main advantage of not assigning a return value to a variable is that you need one less line of code. In PHP, we can commonly do our assignment at the same time as invoking our function:
$sql = "SELECT...";
if(!$query = mysql_query($sql))...
...although this is sometimes discouraged for readability reasons.
In my view for the sake of consistency assigning return values to variables is broadly the better approach, even when performing simple functions.
If you are calling the function over and over, it is probably best to keep this info in a variable. That way the server doesn't have to keep processing the answer, it just looks it up. If the result is likely to change, however, it will be best to keep running the function.
Since you allocate a new variable, this will take a tiny bit more memory. But it might make your code a tiny bit more faster.
The troubles it bring, could be big. For example, if you include another file that applies the same trick, and both store the size in a var $sizeof, bad things might happen. Strange bugs, that happen when you don't expect it. Or you forget to add global $sizeof in your function.
There are so many possible bugs you introduce, for what? Since the speed gain is likely not measurable, I don't think it's worth it.
Unless you are calling this function a million times your "performance boost" will be negligible.
I do no think that it really matters. In a sense, you do not want to perform the same thing over and over again, but considering that it is sizeof(); unless it is a enormous array you should be fine either way.
I think, you should avoid constructs like:
for ($i = 0; $i < sizeof($array), $i += 1) {
// do stuff
}
For, sizeof will be executed every iteration, even though it is often not likely to change.
Whereas in constructs like this:
while(sizeof($array) > 0) {
if ($someCondition) {
$entry = array_pop($array);
}
}
You often have no choice but to calculate it every iteration.
I am somewhat new to PHP, and I am wondering:
How important is it to unset variables in PHP?
I know in languages like C, we free the allocated memory to prevent leaks, etc. By using unset on variables when I am done with them, will this significantly increase performance of my applications?
Also, is there a benchmark anywhere that compares the difference between using unset and not using unset?
See this example (and the article I linked below the question):
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n"; // 120172
echo memory_get_peak_usage() . "<br>\n"; // 121248
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n"; // 120172
echo memory_get_peak_usage() . "<br>\n"; // 201284
As you can see, at one point PHP had used up almost double the memory. This is because before assigning the 'x'-string to $x, PHP builds the new string in memory, while holding the previous variable in memory, too. This could have been prevented with unsetting $x.
Another example:
for ($i=0; $i<3; $i++) {
$str = str_repeat("Hello", 10000);
echo memory_get_peak_usage(), PHP_EOL;
}
This will output something like
375696
425824
425824
At the first iteration $str is still empty before assignment. On the second iteration $str will hold the generated string though. When str_repeat is then called for the second time, it will not immediately overwrite $str, but first create the string that is to be assigned in memory. So you end up with $str and the value it should be assigned. Double memory. If you unset $str, this will not happen:
for($i=0;$i<3;$i++) {
$str = str_repeat("Hello", 10000);
echo memory_get_peak_usage(), PHP_EOL;
unset($str);
}
// outputs something like
375904
376016
376016
Does it matter? Well, the linked article sums it quite good with
This isn't critical, except when it is.
It doesn't hurt to unset your variables when you no longer need them. Maybe you are on a shared host and want to do some iterating over large datasets. If unsetting would prevent PHP from ending with Allowed memory size of XXXX bytes exhausted, then it's worth the tiny effort.
What should also be taken into account is, that even if the request lifetime is just a second, doubling the memory usage effectively halves the maximum amount of simultaneous requests that can be served. If you are nowhere close to the server's limit anyway, then who cares, but if you are, then a simple unset could save you the money for more RAM or an additional server.
There are many situations in which unset will not actually deallocate much of anything, so its use is generally quite pointless unless the logical flow of your code necessitates its non-existence.
Applications being written in languages like C usually run for many hours. But usual php application's runtime is just about 0.05 sec. So, it is much less important to use unset.
It depends, you should make sure you unsetted very long strings (such as a blog post's content selected from a db).
<?php
$post = get_blog_post();
echo $post;
unset($post);
?>