In PHP, I have a callback function using preg_match() (the exact contents are not relevant I think).

Is it better to calculate the result and assign to a variable, and then return that variable, or should I just return the result?

In other words, is it better to do this:

function a() {
   $result = preg_match();
   return $result;


function b() {
   return preg_match();

I'm thinking in terms of code style and performance. Is there a standard I should follow or is it really not important?


After I read @Mark B's answer below, I did some digging into this. Using the method described in, the first method above does indeed result in one more opcode (an ASSIGN) being called.

Written by MPD

@MPD Wow thanks for that! So if I was really micro-optimising I would go with the second one, but as you said before it doesn't make a lot of difference.

Written by Blowski

I don't think it really makes a difference. I don't put 100% trust in timed for-loops as proof for optimizations. Being able to explain why and have proof (asm, opcode, bytecode, etc) is key.

Written by MPD

Accepted Answer

From a performance standpoint there's no difference between the two cases.

Regarding coding style, it's a matter of personal preference. Personally, I would advocate the second, as it's cleaner and easier to read, but I don't think anyone would fault you either way.

Written by eykanal
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki