# TypePHP `std::array` vs PHP Array Performance: How the AOT Compiler Achieves 10x Speedup

> Discover how TypePHP std::array outperforms PHP arrays by 10x. Learn how AOT compilation and native C++ arrays eliminate overhead for blazing fast performance.

- Repository: [Swoole Project/typephp](https://github.com/swoole/typephp)
- Tags: performance
- Published: 2026-08-30

---

**TypePHP's `std::array` container achieves approximately 10 times faster execution than standard PHP arrays by compiling fixed-size, strongly-typed collections into native C++ arrays, eliminating zval overhead and hash-table lookups entirely.**

The Swoole TypePHP AOT compiler introduces `std::array` as a specialized container that bridges PHP syntax with systems-level performance. Unlike generic PHP arrays—which function as hash tables of `zval` structures—the `std::array` implementation maps directly to C++ `std::array` instances, enabling dramatic throughput improvements for computationally intensive workloads.

## Architectural Differences: Compile-Time vs Runtime

### Compile-Time Type Resolution

In [`src/Parser/StdContainerTrait.php`](https://github.com/swoole/typephp/blob/main/src/Parser/StdContainerTrait.php), the `isStdArray()` method detects `std::array` declarations during the parsing phase. This early detection allows the compiler to record element types and dimensions in the compilation context. Because the type and size are known at compile time, the AOT compiler generates direct C++ array index operations rather than dynamic hash computations required by PHP's `HashTable` implementation.

### Elimination of zval Overhead

Standard PHP arrays store every element as a `zval`, which carries type tags, reference counts, and copy-on-write semantics. The `STD_ARRAY` type constant defined in [`src/Type.php`](https://github.com/swoole/typephp/blob/main/src/Type.php) enables the compiler to allocate contiguous memory blocks containing raw primitives—such as `int` or `float`—rather than boxed values. This removes per-element allocations, reference counting checks, and the pointer indirection typical of PHP array access.

### Cache-Friendly Memory Layout

`std::array` allocates elements in contiguous memory, allowing CPU prefetchers to anticipate sequential access patterns and maximize cache line utilization. PHP arrays, by contrast, use hash tables with pointer indirection and unpredictable memory strides, which degrades locality and increases cache miss rates during iteration.

## Native Code Generation Pipeline

During AOT compilation, the `parseStdArrayDimFetch` method in [`src/CompilerBase.php`](https://github.com/swoole/typephp/blob/main/src/CompilerBase.php) transforms PHP array access syntax into direct C++ indexing. An expression like `$arr[$i]` compiles to a raw pointer offset calculation rather than the multi-step hash lookup, collision handling, and zval dereference required by standard PHP execution.

## Measured Performance Advantage

According to the official documentation in [`docs/zh-cn/STD_CONTAINERS.md`](https://github.com/swoole/typephp/blob/main/docs/zh-cn/STD_CONTAINERS.md), benchmarks demonstrate that `std::array` operations run approximately **10 times faster** than equivalent operations on standard PHP arrays when compiled with the Swoole TypePHP AOT compiler. This acceleration stems from the combination of static typing, contiguous memory storage, and direct native code generation.

## Practical Implementation Examples

### Basic Declaration and Access

```php
function demoStdArray(): void {
    // Declares a fixed-size array of 100 integers
    $arr = std::array(Type::Int, 100);
    
    // Compiled to direct C++ array stores (no hash calculation)
    $arr[0] = 123;
    $arr[99] = 456;
    
    // Compiled to direct C++ loads (no zval dereference)
    var_dump($arr[0]);
}

```

### Multi-Dimensional Arrays

```php
function demoMatrix(): void {
    // Creates a 3×4 integer matrix with contiguous allocation
    $matrix = std::array(
        std::array(Type::Int, 4),
        3
    );
    
    $matrix[0][0] = 10;
    $matrix[2][3] = 99;
    
    var_dump($matrix[2][3]);
}

```

### Contrast with Standard PHP Arrays

```php
function demoPhpArray(): void {
    $arr = [];
    for ($i = 0; $i < 100; $i++) {
        // Requires hash-table insertion and zval allocation
        $arr[$i] = $i;
    }
    // Requires hash lookup, collision check, and zval fetch
    var_dump($arr[0]);
}

```

When processed by the TypePHP compiler, the `std::array` examples generate tight C++ loops optimizable by the underlying compiler (including vectorization and loop unrolling), while the PHP array version retains the overhead of the Zend engine's hash table API.

## Summary

- `std::array` in TypePHP compiles to native C++ arrays, eliminating the hash-table overhead and pointer indirection of PHP arrays.
- The `isStdArray()` method in [`src/Parser/StdContainerTrait.php`](https://github.com/swoole/typephp/blob/main/src/Parser/StdContainerTrait.php) enables compile-time type detection, allowing the generation of direct memory access code.
- By storing raw values instead of `zval` structures, `std::array` reduces memory footprint and eliminates reference counting overhead for container elements.
- Official documentation and benchmarks confirm approximately **10x performance improvement** over standard PHP arrays when using AOT-compiled TypePHP code.

## Frequently Asked Questions

### What is the syntax for declaring a std::array in TypePHP?

Declare the container using the `std::array()` function with a type constant from [`src/Type.php`](https://github.com/swoole/typephp/blob/main/src/Type.php) and a fixed size: `$arr = std::array(Type::Int, 100);`. The compiler validates these declarations at compile time, ensuring type safety and enabling optimization.

### Can std::array store mixed types like standard PHP arrays?

No. Unlike PHP's flexible hash tables, `std::array` requires homogeneous types declared at initialization. This constraint allows the compiler to generate type-specific C++ code and maintain contiguous memory layout without type-checking overhead during execution.

### How does the compiler transform array accesses into native code?

The `parseStdArrayDimFetch` method in [`src/CompilerBase.php`](https://github.com/swoole/typephp/blob/main/src/CompilerBase.php) transforms PHP array access syntax into direct C++ index operations. This bypasses the `HashTable` lookup logic and zval handling found in traditional PHP execution, resulting in single-instruction memory access.

### Is the 10x performance gain consistent across all use cases?

The documented 10x speedup applies primarily to numeric indexing and tight iteration loops documented in [`docs/zh-cn/STD_CONTAINERS.md`](https://github.com/swoole/typephp/blob/main/docs/zh-cn/STD_CONTAINERS.md). Performance gains vary based on access patterns, array size, and whether the code runs through the TypePHP AOT compiler versus standard PHP interpretation. Random access patterns still benefit from the elimination of hash calculations, though the margin may differ from sequential benchmarks.