Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Would you rather:

$this->getDoctrine()->getManager()->persist($currency);
$this->getDoctrine()->getManager()->persist($user);
$this->getDoctrine()->getManager()->flush();

or

$em = $this->getDoctrine()->getManager();
$em->persist($currency);
$em->persist($user);
$em->flush();

Is using a aliasing variable for faster coding a smart choice, or should the programmer rather use variables only if they are really variables.

share|improve this question
    
Performance is irrelevant. Less code and easier to read is what matters. –  david.pfx Jul 8 '14 at 10:51

2 Answers 2

I'd prefer the second approach, but with a better variable name.

  • Don't repeat the logic for obtaining the manager (DRY). If this changes, you'll only need to change one place instead of three.
  • Decouples the logic of operating on the manager from obtaining the manager. Extracting it to its own method is only a small step.
  • Assuming you use a good name (not $em) it's more readable.
  • It's potentially faster, but that's only relevant if this is executed in a tight loop, and fetching the manager is a bottleneck. I expect a flush or persist operation to be much more expensive than fetching the manager. So I doubt performance is measurably better.

Introducing local variables is often a good idea, but generally not due to performance improvements.

share|improve this answer

Chained methods are awesome, but I almost always go for the variable approach. Other than what CodesInChaos already mentioned, it's just a lot quicker to interject some code and do some debugging / error handling.

For example, in your code it would probably make sense to check if you've actually instantiated the Entity Manager before you start using it:

$em = $this->getDoctrine()->getManager();

if(!$em) {
    throw new Exception("Hey, where's my entity manager?");
}

$em->persist($currency);
$em->persist($user);
$em->flush();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.