PHP - Faster to use code - php

In general, is code length affective to the speed of the program? I'm talking about differences in small sizes not comparing 10,000 lines to 10.
Example #1:
// Ternary Operator
$todo = (empty($_POST['todo'])) ? 'default' : $_POST['todo'];
VS
// The above is identical to this if/else statement
if (empty($_POST['todo'])) {
$action = 'default';
} else {
$action = $_POST['todo'];
}
And other examples like not using common brackets and universal indentation.
Example #2:
if ($gollum === 'halfling') {
$height --;
}
VS
if ($gollum === 'halfling') $height --;
Also using CamelCase naming convention will lower the characters length, is that effective at all? I doubt this is effective, but still it uses less characters.
Cheers!

In your first example, you are using two different constructs, namely the 'ternary operator' and an 'if / else' statement.
Since the 'if / else' statement is more general (ie you can do more thing with it), the compiler / parser will have more difficulties to optimize it. So I would say that the ternary operator might be a little bit faster.
In the second example, it is only about coding style, both codes will probably be compiled / parsed to exactly the same thing, so no gain here.
However, premature optimization is the root of all evil ! The gain from doing such micro tiny optimization, even on a whole application will probably be negligible and will most of the time be at the expense of readability and maintainability. So I would strongly advice against that kind of thing.
Concerning characters length, it won't matter at all, the compiler / parser will transform that anyway to some other representation that could be understood by the computer, so the only thing that will change is the space that your source code will take on the hard drive.
Just write your code the way it is easier for you to understand and let the compiler / parser do those kind of thing. It is much better to optimize the algorithm itself than the way of writing it.

I think you shoud concern coding style more than efficiency now.
if you already have a style guide, follow it. if you not, you can find one or create one. There aren't such difference between your codes both of two examples. You can pick anyone to create your own style guide.

Related

PHP Style Guide Conformance

For a new project I've just started, I thought it might be a good idea to adhere to a styleguide for my code. I had sort of settled on a style for myself, but could use a little more structure, since there were a few things that varied between my projects and even sometimes within projects.
Now I've settled on this styleguide: http://www.php-fig.org/psr/psr-2/
Question is though, it says to limit lines of code to 80 characters, so I set up a ruler at that limit in ST3. I'm just not sure what a good practice is in regard to splitting code over multiple lines. How would you split the code below (it's already indented by 8 spaces)?
$this->errorMessage = (isset($this->errorDefinitions[$errorNo])) ? $this->errorDefinitions[$errorNo] : $errorMessage;
Or would it be better to conform to the guide by abandoning the shorthand expression and just writing:
if (isset($this->errorDefinitions[$errorNo])) {
$this->errorMessage = $this->errorDefinitions[$errorNo];
} else {
$this->errorMessage = $errorMessage;
}
There's nothing in the styleguide on this subject. Can anyone point me in the right direction or just tell me where I can find more information on the 'proper' way of doing it. I realize there might not be consensus on the way to do it, but I'd like to read your opinions.
You could break up your shorthand across lines:
$this->errorMessage = isset($this->errorDefinitions[$errorNo])
? $this->errorDefinitions[$errorNo]
: $errorMessage;
Just keep in mind that shorthand ternary statements are awesome... when they are short and simple! But once your conditions become longer you are just making your code harder to read, understand, and ultimately maintain. That's why PSR-2 has the line limit (in part).
Your code is a bit in the fuzzy area from my perspective. Breaking it up like above is ok, but if it was any more complicated at all (called a function, etc) I'd say abandon the shorthand and go with the if.
Ultimately it's your call, as you pointed out PSR-2 doesn't land on this issue.

What is the benefit of using multiple steps to complete an if test?

What is the benefit of using multiple steps to test variables:
$VarLength = strlen($message);
if ($VarLength > 10)
echo "Over Ten";
...versus just pushing the whole process into one if statement:
if ( strlen($message) > 10 )
echo "Over Ten";
I'm wondering if the benefits go beyond code style, and the ability to re-use the results of the (in the example above) strlen result.
Your question is not really possible to answer technically, so this is more a comment than an answer.
Benefits beyond code-style and re-use of the result is when you change the code.
You might want to replace the strlen() function with some other function but you don't want to edit the line with the if clause while you do so. E.g. to prevent errors or side-effects. That could be a benefit, however it depends on code-style somehow. So as you exclude coding style from your question, it makes it hard to answer as that domain touches a lot how you can/should/would/want/must write code.
If the result of a function will be used multiple times, it should be cached in a variable so as to obviate the need to waste resources to re-calculate its result.
If the function result won't be re-used, it can simply be a matter of code readability to clearly delineate what's happening by storing the function return value in a variable before using it in an if condition.
Also, in terms of readability, you should always use curly braces even when not mandated by PHP syntax rules as #AlexHowansky mentions.
Most of it is in the code style. In terms of rapidity of the results, it doesn't change much. If you are using $varLenght more then once, then you are saving the call to the function to obtain the length. But even that, the time difference is extremely minimal (I would even like to say unnoticable).
But: When developping any applications, you have to keep in mind that you might not be the only one making changes to it down the road, or you might not be as fresh and up to date with the exact program you are writing. Therefore, the cleaner the code, the easier it is in terms of maintenance, and THAT'S where you save a lot of time down the road.
Best Practice dictates that functions be called minimally. In your case the practice doesn't violate the rule, but it is not uncommon to find code like:
if ( strlen($message) > 100 )
echo "Over Ten";
else if ( strlen($message) > 20 )
echo "Over Ten";
else if ( strlen($message) > 10 )
echo "Over Ten";
...
A common prevention is to always assign function results to a variable for consistency.
I wouldn't say there is any benefit apart from the re-use case you've already mentioned. Your latter case is more readable, probably faster, and probably less memory-intensive. I would however strongly recommend always using braces, even when your conditional is only one line:
if (condition) {
statement;
}

Clarity of using if(count())

In this code fragment:
$results = $this->getAdapter()->fetchAll($query);
if(count($results)) {
// …
}
…do you consider the if(count()) part to be be a well understood idiom, or confusing code. i.e. should it be
if(count($results) > 0)
???
Using a boolean expression with 'if' requires less understanding of a language than using implicit conversions, so I would always prefer the second option (adding "> 0") - at least if this code is meant to be read by others, too. You never know who will maintain your code. The keyword is "clarity" here.
But I must admit I have written many times code with if's using an int expression myself, too, because I like its elegance.
They are doing exactly the same job in this context, and are both easily readable.
I'll just add (just in case) that if you're performing this query only to if(count()), then you should be issuing a SELECT COUNT(*) instead!
The count and the extraneous > comparison are pointless. If you receive an actualy array, then the test should just be:
if ($results) {
That's what scripting languages are for. Abstracting low level details away.
You would only need the count if your fetchAll function returns an ArrayObject or similar. Should your function sometimes return a false for example, then your if (count( is going to fail (because count(false)==1 in PHP).
erm...not realy sure what the purpose of this question is - but the semantics should be self-evident to anyone whom understands PHP
My opinion is that the > 0 check is redundant and unnecessary.
I know other developers who insist that it should be there for clarity, but frankly I can't why -- anyone who can read PHP should be able to discern that they are identical.

Is it good practice to use break and continue in PHP?

Is it a good practice to use break and continue as sentinel for loops in PHP?
e.g.
if (!empty($var))
break;
do {
if (condition1)
break;
some code;
some code;
if (condition2)
break;
some code;
some code;
if (condition3)
break;
some code;
some code;
} while (false);
vs.
if (!condition1) {
some code;
some code;
if (!condition2) {
some code;
some code;
if (!condition3) {
some code;
some code;
}
}
Some find the first version an abhomination and difficult to read and love the second version. Some find the first version cleaner and easier to read. As the number of conditions multiply, I tend to find the first version easier to follow, as the second one tends to get more and more difficult to follow the level of nesting. Also if the if (condition) break; gets into something only slightly more complex like if (condition) {some code; break}, the do {if .. break; if .. break..;} while(false) pattern gets even more clear compared with equivalend nested ifs.
In light usage it is ok, but in heavy usage it makes your code spaghetti. break and continue is basically just a restricted goto and as such, use sparingly.
It absolutely is, they're both valid programming constructs.
What is not a good idea is the newly introduced GOTO. (Please tell me this was an April fool's joke I didn't see the note about!)
It is perfectly correct to use break or continue as long as it helps to make the code easier to read and understand. I personally use them very rarely, and only when I cannot easily use another structure.
In the case of most while statements, it's easier to achieve the same result as a break or continue by using a boolean variable as the condition for the loop in the first place, and then modifying its value inside the loop.
On the other hand, the best use case for the break, in my opinion, is to save resources if you are iterating through an array or something similar with a for or foreach block and are only interested in processing elements until some item is reached. By using a break after reaching this element, it is possible to save on processing power by breaking out of the loop without going over the remaining elements. This makes the code more efficient without making it less legible.
And of course, it is practically impossible to use switch statements without break.
Another exception is if you need to control nested structures, in which case it is sometimes simpler to use break n or continue n than manipulate multiple variables concurrently. (Even though this use case is probably the most controversial...)
In Python, we use infinite loop and break to improve readability. So yes, you can use it, provided you do it correctly, and for a good reason.
Let me answer with a couple of questions:
Why shouldn't it be considered good practice?
Does it reduce readability of your code?
Does it slow down your for cycles?
For a discussion of break and continue in PHP (and looping in general) have a look at Advanced loops - you get the impression that the author can just about manage to swallow break and continue but not break n and continue n. :-)
In 5+ years programming PHP I never had to use break outside of switch statements.
Continue is sometimes used to skip first or last items in iterations, but I don't like it very much.
Why did they reintroduce GOTO ? that's a shame
To answer the question, in
if (!empty($var))
break;
Why not use return (if in a method context)
if (!empty($var))
return false;
I think this way much clear and makes the caller aware of what's happened inside. A better use for argument errors is using Excecptions, which in facte will break execution a the point they are raised.

Should PHP code have spaces before operators?

I've seen a lot of code recently formatted as the following:
A:
if ($var=='test'){
$var=Foo('blah'.$var1);
}else{
// do something
}
Personally I don't like it and would prefer it as:
B:
if ($var == 'test') {
$var = Foo('blah' . $var1);
} else {
// do something
}
I think it's much more readable (note the addition of spaces).
Is there a general preference in the community or is one way better than another?
The most important thing is to follow a standard and stick to it.
That said maybe you can follow Zend's Framework standards and they use spaces. Check C.4.6.
if ($a != 2) {
$a = 2;
}
Hope it helps!
+1 for spaces :)
but that's just my own standard, as long as you are consistent and your code is clear, it should be okay
PHP is much like C in its syntax. As I use both, I tend to follow the same style.
For instance, keywords vs functions:
if ($foo) {
vs
MySuperDuperFunction($foo);
Then you come to a question of indentation:
switch ($bar) {
case CONSTANT:
more_code();
.. is much easier to read as
switch ($bar) {
case CONSTANT:
more_code();
This indicates that the switch and the case are on the same level, which they are. It also helps avoid crazy indentation in yet-to-be-optimal switches.
Your style should illustrate the syntactic sugar of the language you are using. This gets strange with PHP as well as C, because both have forgiving parsers.
If you write something like this:
if($a==2&&b==1&&c>3)
{
I'm going to hunt you down and demand that you pay for my aspirin. The same would go for this:
if (
a==2
&&
b==1
&&
c>3
)
{
... For God sakes man, its not LISP!
It's a matter of convetions that are stablished within your team.
The most famous conventions are Zend Framework and PEAR. You can also create your own, just make sure it is readible.
Personally, I use spaces.
The general advice would be to standardize the code formating, so it meets some best practices, and is widely known, instead of inventing something custom.
PSR-2, the coding style guide would be the best well known approach, accepted by many. here are facts, why it's good to keep the code formatting.

Categories