Tag: PHP

概要

  • "for文でcount()する"と"あらかじめcount()しておく"の比較
  • "foreachでexplode()する"と"あらかじめexplode()しておく"の比較

ソース

<?php

$arr1 = array(1, 2, 3, 4, 5);
$arr2 = "a\nb\nc\nd\ne\n";

function _count()
{
    global $arr1;

    $a = null;
    $b = 0;
    $s = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        for ($j = 0; $j < count($arr1); $j++) {
            $b++;
        }
    }
    $e = microtime(true);
    echo $e - $s;
}

function _cnt()
{
    global $arr1;

    $a = null;
    $b = 0;
    $s = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        $cnt = count($arr1);
        for ($j = 0; $j < $cnt; $j++) {
            $b++;
        }
    }
    $e = microtime(true);
    echo $e - $s;
}

function _explode()
{
    global $arr2;

    $a = null;
    $b = 0;
    $s = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        foreach (explode("\n", $arr2) as $l) {
            $b++;
        }
    }
    $e = microtime(true);
    echo $e - $s;
}

function _buf()
{
    global $arr2;

    $a = null;
    $b = 0;
    $s = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        $buf = explode("\n", $arr2);
        foreach ($buf as $l) {
            $b++;
        }
    }
    $e = microtime(true);
    echo $e - $s;
}

for ($i = 0; $i < 5; $i++)
{
    echo 'count() : ', _count(), "\n";
    echo '$cnt    : ', _cnt(), "\n";
}
for ($i = 0; $i < 5; $i++)
{
    echo 'explode() : ', _explode(), "\n";
    echo '$buf      : ', _buf(), "\n";
}

結果

count() : 0.061480045318604
$cnt    : 0.014682054519653
count() : 0.060186862945557
$cnt    : 0.017099142074585
count() : 0.057183980941772
$cnt    : 0.014756917953491
count() : 0.056124925613403
$cnt    : 0.014930009841919
count() : 0.056313991546631
$cnt    : 0.01494312286377
explode() : 0.025274991989136
$buf      : 0.026523113250732
explode() : 0.025125980377197
$buf      : 0.026413917541504
explode() : 0.025193214416504
$buf      : 0.026408910751343
explode() : 0.025134086608887
$buf      : 0.026459932327271
explode() : 0.025177955627441
$buf      : 0.02644681930542

Last-modified: 2013-07-01 (月) 17:35:36 (1570d)