linna / typed-array

Linna Typed Array,PHP的 typed arrays

v3.0.1 2023-02-08 19:59 UTC

This package is auto-updated.

Last update: 2024-09-10 23:27:13 UTC


README

Linna Logo
Linna dotenv Logo

Tests Quality Gate Status PDS Skeleton PHP 8.1

关于

本包提供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()
]);

注意:允许的类型有:arrayboolcallablefloatintobjectstring和所有现有类。

3.0版本的性能考虑

与库的先前版本相比,这个版本稍微快一些,因为每种类型都有自己的类。毫秒真的很重要吗?

Array Speed Test

2.0版本的性能考虑

与库的第一个版本相比,这个版本稍微慢一些,因为合并了TypedObjectArrayTypedArray之后,在创建新实例和赋值操作时,有更多的代码被执行。

Array Speed Test

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();

Array Speed Testgist上查看速度测试脚本。