首页 > 解决方案 > substr_count()、array_count_values() 和 count() 如何在 PHP 内部工作?在大数据的情况下如何处理性能和速度问题?

问题描述

我试图了解这些功能如何在内部工作以及它们如何处理大数据情况下的性能和速度问题。我知道它们是用 C 编写的,但我想了解它并知道当被问及在 php 中遇到这种情况时我能做什么。我还在 github 上看到了它的 C 代码,比如substr_count,但谁能解释一下。

标签: phparraysstringperformance

解决方案


这些实现非常简单。

数数

// count($a)
it works like `return a.length` in other languages.

数组计数值

// array_count_values(a)
// https://github.com/php/php-src/blob/683123fa39114692b712b8c88d5b2fec9b1fc7ea/ext/standard/array.c
// it works like this:
$r = [];
for($a as $v) {
    $r[$v]++;
}
return $r;

substr_count

// substr_count(p, needle)
if (needle_len == 1) {
    //if there is only one char in needle, just search it in the memory, more effective
    cmp = needle[0];
    while ((p = memchr(p, cmp, endp - p))) {
        count++;
        p++;
    }
} else {
    // just like C's strstr to search
    while ((p = (char*)php_memnstr(p, needle, needle_len, endp))) {
        p += needle_len;
        count++;
    }
}

//or PHP-like version 
//remember: the strchr is strstr in PHP while they are different in C
//so just a demo here
$c = 0;
while($p = strstr($p, $needle)) {
    // get the remaining string
    // in C here is a pointer operation and much more faster
    $p = substr($p, strlen($needle)); 
    $c++;
}

推荐阅读