เทคนิคการตรวจสอบตัวแปรแอเรย์ว่ามีหรือไม่

ตัวอย่างนี้จะเป็นการหาตัวแปรแบบแอเรย์ตำแหน่งที่กำหนด (เช่นหาแอเรย์ตัวที่ 3) ซึ่งเท่าที่คิดออกมี 3 วิธี คือ count(), sizeof() และ isset() โดยผมจะทำการทดสอบเปรียบเทียบว่าวิธีไหนสามารถทำงานได้เร็วที่สุด

การทดสอบชุดที่ 1 มีผลลัพท์
<?php
$max = 10000;
$test = array(1, 2);
// test 1
$start = microtime(true);
for ($z = 0; $z < $max; $z++) {
  if (count($test) == 3) {
    
  }
}
echo '<br>count '.( microtime(true) - $start);
// test 2
$start = microtime(true);
for ($z = 0; $z < $max; $z++) {
  if (sizeof($test) == 3) {
    
  }
}
echo '<br>sizeof '.( microtime(true) - $start);
// test 3
$start = microtime(true);
for ($z = 0; $z < $max; $z++) {
  if (isset($test[2])) {
    
  }
}
echo '<br>isset '.( microtime(true) - $start);

ผลการทดสอบ
count 0.0050919055938721
sizeof 0.0049669742584229
isset 0.00088787078857422

จากผลการทดสอบจะเห็นว่า isset() ทำความเร็วได้ดีที่สุด

การทดสอบชุดที่ 2 ในกรณีที่มีผลลัพท์
// test 4
$start = microtime(true);
for ($z = 0; $z < $max; $z++) {
  if (count($test) == 2) {
    
  }
}
echo '<br>count '.( microtime(true) - $start);
// test 5
$start = microtime(true);
for ($z = 0; $z < $max; $z++) {
  if (sizeof($test) == 2) {
    
  }
}
echo '<br>sizeof '.( microtime(true) - $start);
// test 6
$start = microtime(true);
for ($z = 0; $z < $max; $z++) {
  if (isset($test[1])) {
    
  }
}
echo '<br>isset '.( microtime(true) - $start);

ผลการทดสอบ
count 0.003882884979248
sizeof 0.0037000179290771
isset 0.00068092346191406

เช่นกันครับ isset() ยังคงทำความเร็วได้ดี ทั้งกรณีที่มีผลลัพท์และไม่มีผลลัพท์
ผู้เขียน goragod โพสต์เมื่อ 21 มี.ค. 2560 เปิดดู 3,329 ป้ายกำกับ BenchmarkPHP
^