Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH Faster method for creating injected instances #10265

Merged

Conversation

emteknetnz
Copy link
Member

@emteknetnz emteknetnz commented Mar 22, 2022

~17% faster method for instantiating things via injector

I validated the performance using the following code in my projects PageController

<?php

use SilverStripe\Admin\ModalController;
use SilverStripe\CMS\Controllers\ContentController;

class PageController extends ContentController
{
    protected function init()
    {
        parent::init();

        $time_pre = microtime(true);
        for($i=0;$i<100000;$i++) {
            //$this->injectOld(); // This took 0.2139 seconds 
            $this->injectNew(); // This took 0.1776 seconds 
        }
        $time_post = microtime(true);
        $exec_time = $time_post - $time_pre;
        echo sprintf("This took %.4f seconds", $exec_time);

    }

    private function injectOld()
    {
        $class = ModalController::class;
        $params = ['MyController', 'MyName'];
        $reflector = new ReflectionClass($class);
        return $reflector->newInstanceArgs($params);
    }

    private function injectNew()
    {
        $class = ModalController::class;
        $params = ['MyController', 'MyName'];
        return new $class(...array_values($params));
    }
}

Copy link
Member

@kinglozzer kinglozzer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I can’t see any reason we would be using Reflection here other than old PHP versions (that we no longer have to support)

@emteknetnz emteknetnz force-pushed the pulls/4/new-injection-creator branch from 2a2527c to 984f5dc Compare March 22, 2022 20:50
@emteknetnz
Copy link
Member Author

@kinglozzer are you happy to re-approve/merge post small change (it's still functionally the same)

Copy link
Contributor

@michalkleiner michalkleiner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

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.

None yet

4 participants