linna / typed-array
Linna Typed Array,PHP的 typed arrays
v3.0.1
2023-02-08 19:59 UTC
Requires
- php: >=8.1
Requires (Dev)
- infection/infection: >=0.26
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^10
This package is auto-updated.
Last update: 2024-09-10 23:27:13 UTC
README


关于
本包提供PHP的typed arrays,作为原生ArrayObject的扩展。
需求
本包需要PHP 8.1
安装
使用composer
composer require linna/typed-array
类
用法
use Linna\TypedArrayObject\ArrayOfIntegers; use Linna\TypedArrayObject\ArrayOfClasses; //correct, only int passed to constructor. $intArray = new ArrayOfIntegers([1, 2, 3, 4]); //correct, int assigned $intArray[] = 5; //throw InvalidArgumentException, string assigned, int expected. $intArray[] = 'a'; //correct, int used $intArray->append(5); //throw InvalidArgumentException, string used, int expected. $intArray->append('a'); //throw InvalidArgumentException, mixed array passed to constructor. $otherIntArray = new ArrayOfIntegers([1, 'a', 3, 4]); //correct, only Foo class instances passed to constructor. $fooArray = new ArrayOfClasses(Foo::class, [ new Foo(), new Foo() ]); //correct, Foo() instance assigned. $fooArray[] = new Foo(); //throw InvalidArgumentException, Bar() instance assigned. $fooArray[] = new Bar(); //correct, Foo() instance used. $fooArray->append(new Foo()); //throw InvalidArgumentException, Bar() instance used, Foo() instance expected. $fooArray->append(new Bar()); //throw InvalidArgumentException, mixed array of instances passed to constructor. $otherFooArray = new ArrayOfClasses(Foo::class, [ new Foo(), new Bar() ]);
注意:允许的类型有:array、bool、callable、float、int、object、string和所有现有类。
3.0版本的性能考虑
与库的先前版本相比,这个版本稍微快一些,因为每种类型都有自己的类。毫秒真的很重要吗?
2.0版本的性能考虑
与库的第一个版本相比,这个版本稍微慢一些,因为合并了TypedObjectArray
和TypedArray
之后,在创建新实例和赋值操作时,有更多的代码被执行。
1.0版本的性能考虑
与父类ArrayObject相比,typed arrays在写入时的速度大约慢6倍到8倍。这种慢速是由于不是原生的__construct()
和不是原生的offsetSet()
。
其他操作与原生ArrayObject没有速度差异。
use Linna\TypedArray; //slower from 6x to 8x. $array = new TypedArray('int', [1, 2, 3, 4]); $array[] = 5; //other operations, fast as native. //for example: $arrayElement = $array[0]; $elements = $array->count();
在gist上查看速度测试脚本。