Notizen
PHP - Exemplos Melhoria de Código
Inhalt der Notizen (1)
Seite 1
Evite Variáveis Temporárias
Evitando variáveis temporárias
Sem variáveis temporárias nós evitamos ter um if local o qual pode gerar um resultado indesejado.
function isPositive(int $number) {
if ($number > 0) {
$status = true;
} else {
$status = false;
}
return $status;
}
Nós podemos remover a variável temporária retornando diretamente o status:
function isPositive(int $number) {
if ($number > 0) {
return true;
}
return false;
}
A última refatoração remove o if e finalmente temos o padrão funcional.
function isPositive(int $number) {
return $number > 0 ;
}
Nunca use funções dentro de loops
Never Use Functions inside Loops
I have seen many programmers who tend to make the mistake of using functions inside of loops. If you are doing this intentionally and is ready to compromise performance just for the sake of saving a line of code, then you certainly need to think once again.
Bad Practice:
for ($i = 0, $i <= count($array); $i++)
{
//statements
}
Good Practice:
$count = count($array);
for ($i = 0; $i < $count; $i++)
{
//statements
}
If you take the burden of storing the value returned by the function in a separate variable before the loop, then you would be saving enough execution time as in the first case the function will be called and executed every time the loop runs which can increase the time complexity of the program for large loops.
Strings mais rápidas
Understanding Strings in a Better Way
Take the code snippet as an example and try to guess which statement will run the fastest and which one the slowest.
Code Snippet:
$a = ‘PHP’;
print “This is my first $a program.”;
echo “This is my first $a program.”;
echo “This is my first “.$a.” program.”;
echo “This is my first ”,$a,” program.”;
Guess what, the last and the most uncommon statement of all wins the speed test. The first one obviously loses as the “print” statement is slower than “echo” statement. The third statement wins over the second one as it uses concatenation operation rather than using the variables inline.
The lesser-known last statement wins as there are no string operations being performed and is nothing other than a list of comma-separated strings.
Informationen
- Beschreibung
- Exemplos de melhoria de código para servir de base a outras situações. Criado para entender o processo de pensamento lógico no desenvolvimento de funções melhores.
- Erstellt von
- Vinícius Rezendrix · Okt 2019
- Aktualisiert
- 20 Okt 2019
- Aufrufe
- 12
- Tags
- Bewertung