echo vs variable - php

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.

Related

Php memory size management

im having some trouble with one of my scripts, basically my scripts updates some products, but since is a lot of products if i dont manage carefully the php memoery from my script i get a error of memoery usage, so basically i used unset to release the memory space, now is much better but is not perfect, so im looking on the php docs and i notice a function called memoery_get_usage() to evaluate my script, i found online a simple example of using this method, but something strange is happening that i cant understand why is giving me this result. Basically i created a variable and store some data using a loop and check the memory between the begginning, after the script finish the loop and than when i unset, but the numbers or not what i expect.
Example script:
echo memory_get_usage(). PHP_EOL ;
$a = '';
for($i=0;$i<=100000;$i++){
$a[] = $i;
}
echo memory_get_usage(). PHP_EOL;
unset($a);
echo memory_get_usage(). PHP_EOL;
The results are:
222048
14871264
222232
The strange part is the last numbers, "222232", if i unset the variable, isnt expected to have the initial number memory at the beginning ("222048")?
Hope for someone could explain me.

Call a method twice or create a temp variable?

I got to wondering about the efficiency of this:
I have a csv file with about 200 rows in it, I use a class to filter/break up the csv and get the bits I want. It is cached daily.
I found that many descriptions (can be up to ~500 chars each) have a hanging word "Apply" and it needs chopping off.
Thinking that calling toString() on my object more than once would be bad practice, I created a temp var : $UJM_desc (this code is inside a loop)
// mad hanging 'Apply' in `description` very often, cut it off
$UJM_desc = $description->toString();
$hanging = substr($UJM_desc, -5);
if($hanging == "Apply")
$UJM_desc = substr($UJM_desc, 0 , -5);
$html .= '<p>' . $UJM_desc ;
But could have just called $description->toString() a couple of times, I am aware there is room to simplify this maybe with a ternary, but still, I froze the moment and thought I'd ask.
Call a method twice or use a temp var? Which is best?
I'd just use regex to strip off the end:
$html .= '<p>' . preg_replace('/Apply$/', '', $description->toString());
That said, if $description->toString() gives the same output no matter where you use it, there's absolutely no reason to call it multiple times, and a temporary variable will be the most efficient.
There's also no reason to save $hanging to a variable, as you only use it once.
In general, it depends, and it's a tradeoff.
Keeping a calculated value in a variable takes up memory, and runs the risk of containing stale data.
Calculating the value anew might be slow, or expensive in some other way.
So it's a matter of deciding which resource is most important to you.
In this case, however, the temporary variable is so short-lived, it's definitely worth using.

What does PHP assignment operator do?

I happens to read this http://code.google.com/speed/articles/optimizing-php.html
It claims that this code
$description = strip_tags($_POST['description']);
echo $description;
should be optimized as below
echo strip_tags($_POST['description']);
However, in my understanding, assignment operation in PHP is not necessarily create a copy in memory.
This only have one copy of "abc" in memory.
$a = $b = "abc";
It consumes more memory only when one variable is changed.
$a = $b = "abc";
$a = "xyz";
Is that correct?
should be optimized as below
It's only a good idea if you don't need to store it, thereby avoiding unnecessary memory consumption. However, if you need to output the same thing again later, it's better to store it in a variable to avoid a another function call.
Is that correct?
Yes. It's called copy-on-write.
In the first example, if the variable is only used once then there is not point of making a variable in the first place, just echo the statements result right away, there is no need for the variable.
In the second example, PHP has something called copy on write. That means that if you have two variables that point to the same thing, they are both just pointing at the same bit of memory. That is until one of the variables is written to, then a copy is made, and the change is made to that copy.
The author does have a point insofar as copying data into a variable will keep that data in memory until the variable is unset. If you do not need the data again later, it's indeed wasted memory.
Otherwise there's no difference at all in peak memory consumption between the two methods, so his reasoning ("copying") is wrong.

Why is echo faster than print?

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.

How important is it to unset variables in PHP?

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);
?>

Categories