使用和不使用use关键字导入类的性能

时间:2018-01-10 18:45:21

标签: php

请考虑以下事项:

我有一个做一些温和报道的课程,

示例1

<?php
    namespace App\Log;

    class Reporting
    {   
        private $config;

        function __construct($config)
        {
            $this->config = $config;
        }

        public function ReportSomething($action)
        {
            // blah blah, sends data to a server
        }
    }
?>

然后我也在课堂上多次使用Reporting类:

示例2

<?php
    namespace App\Controller

    use App\Log\Reporting;

    class DoStuff
    {

        public function getUser() 
        {
            // blah blah, business logic
            $reporting = new Reporting($config);
            $reporting->ReportSomething('going to db');
            $reporting->ReportSomething('got data');

            $reporting2 = new Reporting($newConfig);
            $reporting2->ReportSomething('preparing to send');
            $reporting2->ReportSomething('sent');
        }

        public function getPosts() 
        {
            // blah blah, business logic
            $reporting = new Reporting($config);
            $reporting->ReportSomething('going to db');
            $reporting->ReportSomething('got data');

            $reporting2 = new Reporting($newConfig);
            $reporting2->ReportSomething('preparing to send');
            $reporting2->ReportSomething('sent');
        }

        /* you get the point */
    }
?>

我的问题是:性能明智,如果我使用这种类型的风格会产生什么影响:

示例3

<?php
    namespace App\Controller

    class DoStuff
    {

        public function getUser() 
        {
            // blah blah, business logic
            $reporting = new \App\Log\Reporting($config);
            $reporting->ReportSomething('going to db');
            $reporting->ReportSomething('got data');

            $reporting2 = new \App\Log\Reporting($newConfig);
            $reporting2->ReportSomething('preparing to send');
            $reporting2->ReportSomething('sent');
        }

        public function getPosts() 
        {
            // blah blah, business logic
            $reporting = new \App\Log\Reporting($config);
            $reporting->ReportSomething('going to db');
            $reporting->ReportSomething('got data');

            $reporting2 = new \App\Log\Reporting($newConfig);
            $reporting2->ReportSomething('preparing to send');
            $reporting2->ReportSomething('sent');
        }

        /* you get the point */
    }
?>

正如您所看到的,示例3不再使用use关键字进行导入,而是在每次想要获取new \App\Log\Reporting类的新实例时执行Reporting

使用案例是否有任何缺点?一个比另一个更好(基于某些数据或信息),为什么?

1 个答案:

答案 0 :(得分:2)

usenamespace实际上并不访问该类,它们只是将命名空间或类存储为字符串,因此它们将以相对相似的速度运行。鉴于我会以示例2为例,因为它鼓励使用这些关键字提供的组织结构。