++$i ve $i++ PHP arasındaki fark nedir?
++$i $i++ sonrası artış iken ön artıştır.
i sonra ilk ve de referans.i"Take advantage of the fact that PHP allows you to post-increment ($i++) and pre-increment (++$i). The meaning is the same as long as you are not writing anything like $j = $i++, however pre-incrementing is almost 10% faster, which means that you should switch from post- to pre-incrementing when you have the opportunity, especially in tight loops and especially if you're pedantic about micro-optimisations!" - TuxRadar
Daha fazla açıklama için, PHP sonrası incrementation öncesi incrementation vs Bu% 10 havai atfettiği bir geçici değişken depolamak olarak belgelenmiştir.
++$i increments $i, but evaluates to the value of $i+1
$i++ increments $i, but evaluates to the old value of $i.
İşte bir örnek:
$i = 10;
$a = $i++;
// Now $a is 10, and $i is 11
$i = 10;
$a = ++$i;
// Now $a is 11, and $i is 11
$i++ kullanarak hafif bir performansın maliyet bazen yoktur. Gibi bir şey yaptığınızda, bkz
$a = $i++;
Gerçekten bu yapıyoruz:
$temporary_variable = $i;
$i=$i+1;
$a=$temporary_variable;
Short answer:
Biraz düşünürseniz Long answer:, nasıl bu kendiniz uygulamak istiyorum, muhtemelen why önek daha hızlı olduğunu fark edecektir. : Söylenmesi gerçeği, postfix (aslında çoğu zaman) uygulanan using öneki
const T T::operator ++ (int) // postfix
{
T orig(*this);
++(*this); // call prefix operator
return (orig);
}
Eğer değil özel bir nedeniniz olmadıkça postfix'i kaçının. Hız farkı karmaşık veri türleri için oldukça fazla olabilir.
Ben aslında birkaç gün önce bu kadar baktı. Heres my source.
Öncesi ve sonrası artmasını bakarak bir başka yolu 2 tablolarını birleştirmek için kestirme olmasıdır.
Pre-artan bir
// long form
$y = $y + 1;
$x = $y; // any statement using $y
// shorthand
$x = ++$y; // the same statement using $y
Post-artırılmıyor
// long form
$x = $y; // any statement using $y
$y = $y + 1;
// shorthand
$x = $y++; // the same statement using $y
+ + $ I $ i + +% 10 daha hızlı olup olmadığını test etmek için aşağıdaki kodu koştu. Ben, itiraf kod istikrarlı bir sonuç yok ama o zaman bile en az% 10 yakın bazı sayılar görmeliydin. I got yüksek yaklaşık 4-4.5% idi.
<?php
$randomFloat = rand(0, 10) / 10;
$before1 = microtime(true);
for($i=0; $i <1000000; ++$i){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after1 = microtime(true);
echo 'it took '.($after1-$before1) . ' seconds fot ++$i<br />';
$before2 = microtime(true);
for($i=0; $i <1000000; $i++){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after2 = microtime(true);
echo 'it took '.($after2-$before2) . ' seconds fot $i++<br /><br />';
echo '++$i is '.((($after1-$before1)*100)/($after2-$before2)-100).'% faster than $i++';