0

Please consider the codes below.

Code1:

<?php
use App\User;

class SomeController {

    public function getUsers()
    {
        return User::all(); 
    }
}

Code2:

<?php
class SomeController {

   public function getUsers()
   {
      return \App\User::all();
   }
}

I got confused whether these two have that much impact to its performance. I know that the first way of coding seems really the better/nicer way but what if I just want to use the User class just once on my Controller? Which is the better choice for single-used class?

Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54
  • 3
    has nothing to do with performance at all, use what ever you like, its all just references to classes – lagbox Dec 14 '17 at 04:59
  • yes, but in case you have to use that class multiple times, better to import it instead of using the fully qualified name – Wreigh Dec 14 '17 at 05:05
  • 1
    It will matter when you refactor your code. Its easier to change in Namespace, instead of you find/replace it line by line. – Dharma Saputra Dec 14 '17 at 05:10
  • PHP with OOP approach is actually slow, tho. Back to procedural if you need 100% performance. – Chay22 Dec 14 '17 at 05:26
  • @Chay22 well, he;s using laravel, so that's already basically a procedural code – tereško Dec 14 '17 at 07:16
  • @tereško [nope](https://stackoverflow.com/questions/1530868/simple-explanation-php-oop-vs-procedural). think about writing for cli purpose, I even often avoid declaring user function. oh I guess we've different meaning of procedural then – Chay22 Dec 14 '17 at 07:35
  • 1
    @tereško In which way is Laravel "basically procedural code"? I am asking out of curiosity. – common sense Dec 14 '17 at 09:03
  • 1
    @Konafets it's filled with static calls and global state. And that approach is promoted by their documentation. – tereško Dec 14 '17 at 09:04
  • @tereško while I don't know Laravel, that methodology sounds.... urrgghh `:-(`. – Martin Jan 05 '18 at 17:36

1 Answers1

1

Personally, if I know I am going to use a class reference exactly once, I use the full reference in-situ and forget the use. The benefit to the use is that if a class is referenced many times then it is easier to rename the class name or the namespace if use is used (since there are fewer refs to repair).

I would expect that there are no performance improvements one way or the other, and if there were, it would be such a trivial improvement that a better server would be an easier way to realise those speed benefits. I tend to advocate against trying to squeeze performance improvements this way, as it encourages reducing readability over benefits that are too small to be noticeable.

This sort of consideration may also be a premature optimisation, i.e. an optimisation that wastes engineering effort on something that is not actually a problem (either now or in the future). There is a good discussion on that here.

halfer
  • 19,824
  • 17
  • 99
  • 186