tags:

views:

139

answers:

4

What is faster: writing PHP code using functions or writing it as pure script? So, as I see it Apache or any other server will create from PHP code using functions a pure script... I mean we had:

function foo($a, $b){ return ($a + $b); }

echo foo(4, 5);

and PHP will turn it into something like:

echo 9;

Or will it?

+17  A: 

There should be no noticeable difference in speed whether you break your code into functions or not - but it will be much easier to maintain and read if you break sections out into logical functions and re-use them when appropriate.

Austin Fitzpatrick
+1 do NOT think about optimization on this level. Never ever. It's totally pointless. High-quality, well structured, maintainable, clean code is much, much more important.
Pekka
Thoughts in order to build something:* Make it work* Make it readable (hence it could be fixed / changed over time)* Apply design patterns.* Optimize/normalize
Alfabravo
+1, it reminded me a some kind of proverb: "If you write a best program you can then you won't be able to debug it." :)
MartyIX
+3  A: 

You really shouldn't worry about this. Structure and maintainability should always take priority over performance.

The difference between them will be infinitesimal, so just use whatever makes life the easiest for you.

Will Vousden
A whole minute?! I can't wait that long! ... Oh, the other pronunciation... n/m.
Adam Bellaire
@Adam: Good point!
Will Vousden
+1  A: 

The speed gain comes from easier to understand code. If your talking about MASSIVE amounts of code, the functions/classes approach is better as its DRY and not procedural. Non procedural means less code.

And again, if were talking about a very large amount of code, this will be quicker...

Glycerine
+1  A: 

If you work on any medium-size project, you will never ever need this kind of optimimization. The optimization you wrote about is usual in languages that are compiled (C++ for example) but I don't think that scripting languages do this (there's simply too little time to do it).

Generally

Standard approach is to write an application and if it works bad then (and only then) optimize it. Many people are tempted to think about optimalization too soon but it's simply wrong. You may think that it's nonsense but if you have the task completed then you can improve your code how long you want and you won't be stressed by deadlines.

PHP

  • First tip, that really holds for any programming language, is to write good algorithms (the ones wit low time complexity). You may do all crazy tricks to gain some more performance but it will be for nothing if you use one bad algorithm.
  • If you really need a performance boost then you may think about accelerators (http://en.wikipedia.org/wiki/PHP_accelerator).
  • http://blogs.digitss.com/php/php-performance-improvement-tips/
MartyIX