ทดสอบความเร็วในการแปลง string เป็น array

ถึงคราวของฟังก์ชั่นในกลุ่มของการแปลงข้อความเป็นแอเรย์ ฟังก์ชั่นในกลุ่มนี้ก็จะมีที่ยอดนิยมอยู่ 3 ตัว คือ explode() preg_split และ preg_match_all()
$string = 'one,two,three,four,five';

แบบแรก ใช้ฟังก์ชั่น explode()
$c = explode(',', $string);

แบบที่สองใช้ฟังก์ชั่น preg_split()
$matches = preg_split("/,/", $string);

แบบสุดท้ายใช้ฟังก์ชั่น preg_match_all()
preg_match_all('/[^,]+/', $string, $matches);

ผลการทดสอบ บน PHP 4 เวอร์ชั่นบนเครื่องเดียวกัน
Current PHP version: 7.1.0-dev
0.049366760253906 (explode)
0.067701864242554 (preg_split)
0.11348605155945 (preg_match_all)

Current PHP version: 5.6.14
0.096615290641785 (explode)
0.14282207489014 (preg_split)
0.23365360498428 (preg_match_all)

Current PHP version: 5.4.45
0.25175402164459 (explode)
0.54272105693817 (preg_split)
0.92153443098068 (preg_match_all)

Current PHP version: 5.2.17
0.13958164453506 (explode)
0.23908882141113 (preg_split)
0.38434380292892 (preg_match_all)

จะเห็นว่าฟังก์ชั่น explode() จะทำงานได้เร็วที่สุด และ preg_split() ก็ยังทำงานได้เร็วกว่า preg_match_all() ครับ
อีกเรื่องหนึ่ง ผลลัพท์ของฟังก์ชั่น preg_match_all() จะแตกต่างจาก ฟังก์ชั่นอื่นเล็กน้อยนะครับ การนำไปใช้ให้ตรวจสอบรูปแบบผลลัพท์ก่อนนำไปใช้ด้วยนะครับ

โค้ดที่ใช้ในการทดสอบ
<?php
// จำนวนครั้งการทดสอบ
$max = 100000;
// จำนวนรอบการทดสอบ ผลลัพท์เฉลี่ยจากค่านี้
$count = 20;
// แอเรย์เก็บผลลัพท์
$ret = array(0, 0, 0);
// ข้อมูล
$string = 'one,two,three,four,five';
for ($m = 0; $m < $count; $m++) {
    // test 1
    $start = microtime(true);
    for ($z = 0; $z < $max; $z++) {
        $c = explode(',', $string);
    }
    $ret[0] += microtime(true) - $start;

    // test 2
    $start = microtime(true);
    for ($z = 0; $z < $max; $z++) {
        $matches = preg_split("/,/", $string);
    }
    $ret[1] += microtime(true) - $start;

    // test 3
    $start = microtime(true);
    for ($z = 0; $z < $max; $z++) {
        preg_match_all('/[^,]+/', $string, $matches);
    }
    $ret[2] += microtime(true) - $start;
    sleep(1);
}
echo 'Current PHP version: '.phpversion().'<br>';
echo ($ret[0] / $count).' (explode)<br>';
echo ($ret[1] / $count).' (preg_split)<br>';
echo ($ret[2] / $count).' (preg_match_all)<br>';
ผู้เขียน goragod โพสต์เมื่อ 07 พ.ย. 2558 เปิดดู 3,264 ป้ายกำกับ benchmark
^