php - substr_count()、array_count_values() 和 count() 如何在 PHP 内部工作?在大数据的情况下如何处理性能和速度问题?
问题描述
我试图了解这些功能如何在内部工作以及它们如何处理大数据情况下的性能和速度问题。我知道它们是用 C 编写的,但我想了解它并知道当被问及在 php 中遇到这种情况时我能做什么。我还在 github 上看到了它的 C 代码,比如substr_count,但谁能解释一下。
解决方案
这些实现非常简单。
数数
// 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++;
}
推荐阅读
- python - Python 3.7:使用 pyinstaller 创建 exe 文件时出错
- django - 模板 Django 中未显示分页数据
- javascript - 在 React-Admin 中保存自定义组件的更改
- sql - 如何根据计数过滤数据而不击中子表/子查询两次?
- javascript - Angularjs - ui-select 的必填字段验证
- esp8266 - ESP01 连接到 PC 时正常,不使用电池启动
- vue.js - [Vue 警告]:v-on 处理程序中的错误:“ReferenceError:分配给未声明的变量顺序”
- javascript - 排序功能说明
- sprite-kit - 在 WatchKit 应用程序中全屏删除数字时钟
- html - 如何更改移动设备的表格列顺序