Skip to content

[12.x] new $class instead of reflection for better performance - #58391

Merged
taylorotwell merged 1 commit into
laravel:12.xfrom
takaram:faster-instantiation
Jan 15, 2026
Merged

taylorotwell merged 1 commit into
laravel:12.xfrom
takaram:faster-instantiation

Conversation

@takaram

@takaram takaram commented Jan 15, 2026

Copy link
Copy Markdown
Contributor

This PR replaces ReflectionClass::newInstanceArgs($args) with new $className(...$args).
This will make the container faster.

Quick benchmark of reflection vs constructor

constructor.php
<?php

class Foo {
    public function __construct(
        public int $a,
        public string $b,
        public array $c,
    ) {
    }
}

$className = Foo::class;
$args = [1, 'example', [1, 2, 3]];

const LOOP = 1000000;

$start = hrtime(true);
for ($i = 0; $i < LOOP; $i++) {
    $instance = new $className(...$args);
}
$end = hrtime(true);
$duration = ($end - $start) / 1_000_000;
echo "Dynamic constructor invocation took {$duration} ms\n";
reflection.php
<?php

class Foo {
    public function __construct(
        public int $a,
        public string $b,
        public array $c,
    ) {
    }
}

$className = Foo::class;
$reflectionClass = new ReflectionClass($className);
$args = [1, 'example', [1, 2, 3]];

const LOOP = 1000000;

$start = hrtime(true);
for ($i = 0; $i < LOOP; $i++) {
    $instance = $reflectionClass->newInstanceArgs($args);
}
$end = hrtime(true);
$duration = ($end - $start) / 1_000_000;
echo "ReflectionClass::newInstanceArgs: {$duration} ms\n";

new $className(...$args) is about 26% faster than $reflectionClass->newInstanceArgs($args).

reflection constructor
1 393.118259 ms 272.36958 ms
2 383.492222 ms 291.622618 ms
3 376.930884 ms 286.945082 ms
Average 384.51 ms 283.65 ms

@taylorotwell
taylorotwell merged commit aad1f10 into laravel:12.x Jan 15, 2026
70 of 72 checks passed
@takaram
takaram deleted the faster-instantiation branch January 15, 2026 20:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants