As discussed in the question Concatenation or data sequencing: which performs best?, This kind of performance concern about language doesn’t make much sense. It is known that PHP was not created to be a performative language, so micro-optimizations in the code will not alter the result and should be avoided when making them legibility and semantics are impaired. Always prefer the code that is easier to read than the one that is supposedly faster.
You ask if there is a performance difference between the two codes, there is no, except if you run it thousands of times to then start seeing some difference. The resource consumption of the two solutions is the same. Even if in the second there is a variable and in the first no, PHP will need to store the return of the function in memory anyway, the difference is that with the variable the value will be accessible to the developer (directly).
Even if there is no difference in performance, you ask which is best. In my opinion, neither of the two are difficult to read and are unclear as to the objective. Reading the documentation, it is possible to notice that the parameter N
of date
will return a number referring to the day of the week of a given date: 1 for Monday, 7 for Sunday. If you are checking if it is equal to 3, you need to know if a certain date is a Wednesday. None of the ways makes this clear.
The way I would do it is:
$isWednesday = (date('N', strtotime($data)) === "3");
if ($isWednesday) {
...
}
This way, I don’t need to resort to the documentation of the function date
to know what the code is doing, because the variable name tells me I’m checking if it’s Wednesday.
In relation to performance there is a difference, the second form has one more variable, that is, one more space in the memory being allocated. Now which form is more beautiful, it varies from person to person. I prefer the first
– Roberto de Campos
Well placed by @Robertodecampos. I particularly always value the performance.
– Andrei Coelho
If you need the value in
$d
later, the second form is better; if not, the first would be better.– Sam
@Andreicoelho then I recommend reviewing some concepts. PHP was not meant to perform, so these differences, as asked, are irrelevant to the application, making readability and semantics always a priority. If such a performance difference is relevant to the application, PHP is not the most suitable language.
– Woss
In addition, the resource used in both codes are the same, since PHP needs to store the return of the function in memory to use in the expression validation. The difference is that with the variable it value is accessible by the developer.
– Woss