Spaces, line breaks, tabs ; are they affect server performance? - php

Spaces, line breaks, tabs ; are they affect server performance ?
I'm in the road of learning PHP and before I go further with my current coding style, i want to make sure :
Are line breaks and spaces affect the performance of the server ? Usually, I always add them for readibility. for example in the following code :
import('something') ;
$var = 'A' ;
$varb = 'B' ;
switch($var) {
case 'A' :
doSomething() ;
doAnotherThing() ;
break ;
}
if ($var == $varb) { header('Location: somewhere.php') ; }
Summary,
I add space before a semicolon
I add space after and before variable value assignment and comparison
I add space between ) and {
Usually I add a line break after { if the code following it consist of multiple statements.
Inside the curly bracket, I always start with a space before the first statement and ended it with another space after the last statement's semicolon
I always give a 2-space-width tab for every child elements
I always add a space after 'Location:' inside header function.
I always add space before semicolon for each case condition
This style is cool for me, I like it, its tidy and it makes me easier to debug, what i wonder is, will this kind of coding style hurt/burden the system ? Will it makes server slower by re-formatting my codes ? So far i got no formatting error.
Thank you for your kind answers

No. The extra formatting will not affect performance at all*.
Choose the coding style you like -- that is also acceptable for the team/project/existing code -- and, most importantly, be consistent. (Using an editor with customizable syntax formatting is helpful.)
Happy coding.
*While it could be argued that an insignificant increase IO may occur and an insignificant greater amount of symbols must be read by the lexer, the final result is: there will be no performance decrease.

No and yes (but mostly insignificant). Slightly different way thinking about the issue from #pst's answer (not even thinking about disk io) but same end result.
Simplified php behind the scenes - PHP is compiled to bytecodes on runtime. During compile, all spaces and comments are filtered down/out among many other actions.
Filtering out more whitespace from less is mostly insignificant compared with all the other actions.
The compiled bytecodes are what actually gets run.
But let's say you are running a major website, have 1000s of web servers and each php file is getting called millions of times a day. All those previously insignificant bits of time add up. But so does all the other stuff that the compiler is doing. At the point that this all becomes an issue for you, it's time to start looking into PHP caching/accelerators. (Or more likely long before this.)
Basically, those cachers/accelerators cache the compiled bytecodes the first time they are produced after the files are modified. Subsequent calls to the same file skip the compiling phase and go right to the cached compiled bytecodes. At that stage all the whitespace no longer exists. So, it becomes a moot point because they only ever compile once.

Related

PHP - Faster to use code

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.

Difference between # and // in php?

<?php
# some comment
?>
and
<?php
// some comment
?>
are used for single-line code commenting in PHP, and that former comes from shell scripting and // comes from C++.
However I am curious to know if there are any differences between using // and # for single line commenting and anyone has come across cases specific cases where one or other should not be used.
Only difference I could think of is there is one character in '#' and two in '//' so perhaps will there in larger scripts some small size and/or performance gains ??
For me it's easier to type // by double pressing the key on my keyboard moving just my right pinky one key down and pressing it two times.
If I want to do # I need to use both hands and the movements are "bigger" ;). It's the same for echo and print.
But in print and echo "scenario" you can hear an argument that one function is a little slower, however I am not sure right now which one ;) but it's really something that is no deal-breaker when optimizing for code I guess.
According to this topic echo is a little faster:
Should I use echo or print in php scripts?

Will the code after false "if" statements be compiled

if I have code like that
if($abc==true) {
//code code code
} else {
// other code, other code
}
So if $abc is true will the "other code" be compiled?
So is this irrelevant if there is a lot of "code" performance wise?
PHP is a parsed (and therefore "compiled") at runtime. All of the code is processed, regardless of reachability. For instance:
<?php
echo "Hello, World!";
exit;
DERP!!
?>
Will fail with a Parse Error rather than printing "Hello, World!", even though the derp can't ever be reached.
Yes, it will be compiled (actually read, tokenized and parsed); PHP has no way of knowing what value will be assumed by $abc at runtime.
You can reduce the load somewhat (but only if it is REALLY a lot of code!) by using include() inside the IFs:
if (condition)
{
include('true.php');
}
else
{
include('false.php');
}
But note that this way you will load two files instead of one. Usually, the overhead of the extra file makes the game not worth the effort.
However, if the IF is really a lot lot lot of code, then dividing it in several files might be a good idea maintenance-wise. Refactoring to remove the IF from the program flow would be even better!
Although the entire code is 'parsed' for errors at runtime, the flow of code will only go in one direction at that 'if' point, so there's basically no speed performance issue.
It's really not worth worrying about, especially since flow control statements such as 'if' are probably the most vital elements of programming. You can't get by without them, really.
What performance problems are you concerned about? PHP is an interpreted language which means your files are parsed, tokenized, and executed on every request. The entire file needs to be parsed and tokenized for syntax errors no matter what. What is executed depends on your control flow statements, like the if in your example.
If you're concerned about extra parsing, you can refactor your code to include another file based on the result of a control flow statement.
$x = 1;
if($x === 1) {
include_once './myFile.php';
}
else {
// Something Else.
}
Though I can't really think of a huge reason related to performance as to why you would want to do that.

Is there an automated way of fixing one line ifs in PHP?

I don't know if it's just me or not, but I am allergic to one line ifs in any c like language, I always like to see curly brackets after an if, so instead of
if($a==1)
$b = 2;
or
if($a==1) $b = 2;
I'd like to see
if($a==1){
$b = 2;
}
I guess I can support my preference by arguing that the first one is more prone to errors, and it has less readability.
My problem right now is that I'm working on a code that is packed with these one line ifs, I was wondering if there is some sort of utility that will help me correct these ifs, some sort of php code beautifier that would do this.
I was also thinking of developing some sort of regex that could be used with linux's sed command, to accomplish this, but I'm not sure if that's even possible given that the regex should match one line ifs, and wrap them with curley brackets, so the logic would be to find an if and the conditional statement, and then look for { following the condition, if not found then wrap the next line, or the next set of characters before a line break and then wrap it with { and }
What do you think?
Your best bet is probably to use the built-in PHP tokenizer, and to parse the resulting token stream.
See this answer for more information about the PHP Tokenizer: https://stackoverflow.com/a/5642653/1005039
You can also take a look at a script I wrote to parse PHP source files to fix another common problem in legacy code, namely to fix unquoted array indexes:
https://github.com/GustavBertram/php-array-index-fixer/blob/master/aif.php
The script uses a state machine instead of a generalized parser, but in your case it might be good enough.

Find function and line number where variable gets modified

Let's say that at the beginning of a random function variable $variables['content'] is 1,000 characters long.
This random function is very long, with many nested functions within.
At the end of the function $variables['content'] is only 20 characters long.
How do you find which of nested functions modified this variable?
Not sure how you'd want to return it but you could use the magic constant __LINE__. That returns the line of the current document.
You could create a variable called $variables['line'] and assign __LINE__ as the value, where appropriate.
If it were me, first I'd consider breaking apart the 1000-line beast. There's probably no good reason for it to be so huge. Yes, it'll take longer than just trying to monkey-patch your current bug, but you'll probably find dozens more bugs in that function just trying to break it apart.
Lecture over, I'd do a search/replace for $variables['content'].*=([^;]*); to a method call like this: $variables['content'] = hello(\1, __LINE__);. This will fail if you are assigning strings with semicolons in them or something similar, so make sure you inspect every change carefully. Write a hello() function that takes two parameters: whatever it is you're assigning to $variables['content'] and the line number. In hello(), simply print your line number to the log or standard error or whatever is most convenient, and then return the first argument unchanged.
When you're done fixing it all up, you can either remove all those silly logging functions, or you can see if 'setting the $variables['content'] action' is important enough to have its own function that does something useful. Refactoring can start small. :)
I think this is a problem code tracing can help with.
In my case I had this variable that was being modified across many functions, and I didn't know where.
The problem is that at some point in the program the variable (a string) was around 40,000 characters, then at the end of the program something had cut it to 20 characters.
To find this information I stepped through the code with the Zend debugger. I found the information I wanted (what functions modified the variable), but it took me a while.
Apparently XDebug does tell you what line numbers, in what functions the variables are modified:
Example, tracing documentation, project home, tutorial article.

Categories