What code cost more at performance level - php

Every body knows that today technology is low cost and many of us don't really care about it. So, take a look to this codes:
Approach #1
$Obj = new Obj();
if (!empty($val1)) {
$Obj->setVal1($val1);
}
if (!empty($val2)) {
$Obj->setVal2($val2);
}
if (!empty($val3)) {
$Obj->setVal3($val3);
}
if (!empty($valN)) {
$Obj->setValN($valN);
}
Approach #2
if (!empty($var1) && !empty($var2) && !empty($var3) && !empty($varN)) {
$Obj = new Obj();
if (!empty($val1)) {
$Obj->setVal1($val1);
}
if (!empty($val2)) {
$Obj->setVal2($val2);
}
if (!empty($val3)) {
$Obj->setVal3($val3);
}
if (!empty($valN)) {
$Obj->setValN($valN);
}
}
In the first example we're creating and object and leave around if none of the values exists, in the second one we are checking first if the values exists and aren't empty and then create the object and set the values. From your perspective which one would be the best solution in performance levels? Which one would you write on your codes?
Note: N is not infinite

Usually it's not operations like empty() or isset() that wastes time. Instead higher memory usage and memory leakage tends to lead to more GC operations, new() performs initialization that takes time, I/O operations causes delay, and that is where you should do your improvement.
It can be very very complex if you want to discuss the time usage in detail: during compilation, runtime, whether the code will run at all etc.

that is depend on what you want,
the first code will set value if it's not empty even tho' another value might be empty,
but the second code would check all of the value first, so if one of the value is empty, it will never create the Obj.
that is a clear choice,
if you think all value is important and necessary, then go with the second code, if it's fine to leave another value empty and want to update any value that is not empty there's no point on using the second code

Related

PHP behavior under the hood

I was just wondering how PHP works under the hood in this certain scenario. Let's say I have these two pieces of code:
function foo() {
return 2 * 2;
}
// First.
if (foo()) {
bar(foo());
}
// Second.
if (($ref = foo())) {
bar($ref);
}
Now the questions:
In the first case, does PHP make some sort of temporary variable inside the if clause? If so, isn't the second piece of code always better approach?
Does the second case take more memory? If answer to the first question is yes to the first question, then not?
The two codes are not equivalent, because the first one calls foo() twice (if it returns a truthy value). If it has side effects, such as printing something, they will be done twice. Or if it's dependent on something that can change (e.g. the contents of a file or database), the two calls may return different values. In your example where it just multiplies two numbers, this doesn't happen, but it still means it has to do an extra multiplication, which is unnecessary.
The answer to your questions is:
Yes, it needs to hold the returned value in a temporary memory location so it can test whether it's true or not.
Yes, it uses a little more memory. In the first version, the temporary memory can be reclaimed as soon as the if test is completed. In the second version, it will not be reclaimed until the variable $foo is reassigned or goes out of scope.
In the first case, you are calling a function twice, so, if the function is time consuming, it is inefficient. The second case is indeed better since you are saving the result of foo().
In both cases, PHP needs to allocate memory depending on what data foo() generates. That memory will be freed by the garbage collector later on. In terms of memory both cases are pretty much equivalent. Maybe the memory will be released earlier, maybe not, but most likely you won't encounter a case where it matters.
PHP can't make any temporary variable because it can't be sure that foo()'s returning value will always be the same. microtime(), rand() will return different values for each call, for example.
In the second example, it takes indeed more memory, since PHP needs to create and keep the value in memory.
Here is how to test it :
<?php
function foo() {
return true;
}
function bar($bool) {
echo memory_get_usage();
}
if (1) {
// 253632 bytes on my machine
if (foo()) {
bar(foo());
}
} else {
// 253720 bytes on my machine
if (($ref = foo())) {
bar($ref);
}
}

Coding Style: function calls inside statements

Ok, first of all, i suspect this is going to be closed.
Right, i have a question relating to using function calls inside statements as opposed to assigning to a variable first.
For example:
(code is in php, but question applies generally. Also, code is overly simplified)
if (myAmazingFunction() === true) {
// do something amazing
}
instead of
$amazingresult = myAmazingFuncton();
if ($amazingResult === true) {
// do something amazing
}
The question is:
Is there any performance, or other underlying pros or cons to each approach
Stylistically, is any of the approaches considered better than the other
In most languages, there will be no performance difference. In the first case, the compiler will allocate storage for the result of the function call before checking whether it is true. In the second case you're simply making this explicit.
If you are debugging, sometimes the second form is easier, as you can set a breakpoint on the second line and check the value returned by the function before the comparison is made - but then you see the result of the function by the path the executing code takes anyway in the example you've given. You can also re-use the value without rerunning the function, as Zac says in his comment.
Stylistically, this is going to be largely subjective. The only thing I'd say here is that if your variable name makes the purpose of the function output clear, then you might be adding something to the ability for others to understand your code easily.
#DavidM's answer is correct. However, I'd just like to add that stylistically, I think it depends on the name of the function and its context.
Example:
if ($food->tastesGood()) {
echo 'Mmmm!';
}
// vs.
$foodTastesGood = $food->tastesGood();
if ($foodTastesGood) {
echo 'Mmmm!';
}
In this case, it's very clear that the return value of the method tastesGood() is going to be a boolean from both the name of the method and its context. Using a temporary variable adds nothing to your code except making it redundant and less-readable at a glance. In addition, if the variable is not defined right before its used, then you have to go find the definition to understand the condition. In these cases, I would say use of a variable is worse.
Another example:
if ($dishes->wash() !== FALSE) {
echo 'Sparkly!';
}
// vs.
$dishesAreClean = $dishes->wash() !== FALSE;
if ($dishesAreClean) {
echo 'Sparkly!';
}
In this case, we can't really infer the return type of the wash() method from its name, and indeed, it would seem that it returns nothing on success and FALSE on errors. Checking if the dishes are clean then requires us to make sure that there were no errors, but the first case doesn't make for particularly readable or self-documenting code. The second case, however, adds very explicit information about what's going on by way of the temporary variable. In these cases, I would say use of a variable is better.
Is there any performance, or other underlying pros or cons to each approach
Performance-wise, assigning an extra variable that you will use only in your if condition will use extra memory, and one useless line of code. So it will use more memory. Will it be noticeable? Probably not.
Stylistically, is any of the approaches considered bad
Using the method in your if statement is perfectly valid, and I think it's a better approach, since you can read the code and see exactly what value is being tested in the if condition. No need to look for the variable and search where it was affected.

Probability in conditional statements

Lets take a variable called someInt which might have any numeric value. We need to check if it's 0 or not.
if($someInt!=0) {
// someInt is not 0, this is the most probable
} else {
// someInt is 0.
}
//VS
if($someInt==0) {
// highly unlikely... perform a jump
} else {
}
Which way is more optimal? Is there any difference (besides readability)?
Another sort of related thing I'm wondering: I have a habit of checking arrays if they any items this way:
if($myArray.length != 0) {
}
// instead of
if($myArray.length > 0) {
}
Notice the " != ". Since array.length can only be 0 or greater than 0, is the "!=" check more optimal?
I'm asking this because I've always done it this way in Visual Basic 6, it apparently worked faster there. What about other languages?
Most probable conditions should be at the top. This way, the parser skips the less probable cases, and you get an overly more optimized application.
Your second question is micro-optimization. I doubt it'll make a difference one way or another in terms of performance.
For the if statement the more likely the case the higher up in the if statement you should make it, from a readability point this makes more sense and from a performance point as well. As for the array section $array.length > 0 is more readable. But, the performance shouldn't be an issue as this should not be called all that often, it is better to cache the result than it is to constantly check the array length.

Is there a way to check if the function expects a return value when called

I want to write a condition where I want to know if my function needs a return value or it can be executed as a procedure. Basically it should look like:
foo($x) {
$x++;
echo $x;
if(is_return_needed()) {
return $x;
}
}
where is_return_needed() is the condition if a return value is needed.
And how it should work:
echo foo(50); // should print AND return 51
bar(foo(50)); // should print AND return 51 to bar() function
foo(50); // should only print the value, because the returned value will not be used
And please don't tell me there's no reason to do this. I know I can send an additional boolean argument to the function which will be the condition, but is there a better way to achieve this?
Returning an object (or a large string), PHP will not make a copy of that object/string. That means returning alone, will not slow down your application. I found an article that explains it pretty well.
If the function can avoid building this large object at all, it will become faster. If you change the result of the function outside, or change it just before returning, it will become slower (is has to do the copy then). Building a long string with always adding a small part is very expensive, because every time it has to allocate a new big block of memory.
That said, we would have to see your code, to understand the slowdown you described. Returning a result only sometimes, is a very bad advice, every developer using your code will have a hard time to understand this behaviour. Sooner or later your application will become unstable if you use this often. Actually i find it even dangerous to return mixed typed values, as PHP often does itself.

When are do loops useful?

As you all probably know, do loops execute at least once, even if the statement is false — while the while loop would never execute even once if the statement is false.
When are do loops useful? Could someone give me a real life example?
They're basically useful when you want something to happen at least once, and maybe more.
The first example that comes to mind is generating a unique ID (non sequentially) in a database. The approach I sometimes take is:
lock table
do {
id = generate random id
} while(id exists)
insert into db with the generated id
unlock table
Basically it will keep generating ids until one doesn't exist (note: potentially an infinite loop, which I might guard against depending on the situation).
The Do loop is very powerfull if you have to check multiple files etc. Due to the guarentee of iteration it will work all the way through.
do {
if($integer > 0) { $nameoffile[0]++; }
else { $nameoffile[0] = $nameoffile[0].$integer; }
$integer++;
} while(file_exists("directory/".$nameoffile[0].".".$nameoffile[1]));
Next to what has already been answered, you can do crude stuff like this with a do:
do
{
if ($cond1) break;
if ($cond2) continue;
do_something();
} while(true/false);
Which is a modification of a switch loop, which allows continue. You can simulate goto similarities in case goto is not available and similar.
It must not make your code more readable, so it's often not suggested to do that. But it technically works.

Categories