<?php

bcscale(15);

function letterSequencePregSplit($string) {
    $stringAsArray = preg_split('//u', $string, null, PREG_SPLIT_NO_EMPTY);
	$arrayCount = count($stringAsArray);
	
    for ($i = 0; $i < $arrayCount; $i++) {
        yield $stringAsArray[$i];
    }
}

function letterSequenceMbSubstr($string) {
    $stringLength = mb_strlen($string);

    for ($i = 0; $i < $stringLength; $i++) {
        yield mb_substr($string, $i, 1);
    }
}

function getAverageDurationFor(callable $generator, $string, $attempts = 1000) {
    $timeOverall = 0;

    for ($i = 0; $i < $attempts; $i++) {
        $timeStart = microtime(true);
        foreach ($generator($string) as $letter) {}
        $timeEnd = microtime(true);
        $timeOverall = bcadd($timeOverall, bcsub($timeEnd, $timeStart));
    }

    return bcdiv($timeOverall, $attempts);
}

function doBenchmark($startLength, $endLength, $step) {
    $string = 'å';
    for ($length = $startLength; $length < $endLength; $length += $step) {
        echo sprintf("string length: %s\n", $length);
        echo sprintf("preg_split: %s\n", getAverageDurationFor('letterSequencePregSplit', str_repeat($string, $length)));
        echo sprintf("mb_substr:  %s\n\n", getAverageDurationFor('letterSequenceMbSubstr', str_repeat($string, $length)));
   }
}

doBenchmark(1, 500, 50);
