What are some good PHP performance tips?

前端 未结 13 1719
挽巷
挽巷 2020-12-24 07:55

I\'ve heard of some performance tips for PHP such as using strtr() over str_replace() over preg_replace() depending on the situation.

相关标签:
13条回答
  • 2020-12-24 08:01

    You must measure before you optimize. Without measurements, you cannot have goals. Without goals, you are wasting your time.

    If you discover that your webpage takes 250ms to render, is that fast enough? If not, how fast should it be? It won't get down to zero. Do you need it to be 200ms?

    Use a tool like XDebug (http://www.xdebug.org/) to determine where the hotspots in your code are. Chances are you will find that your app is taking 80% of its time accessing the database. If your app is taking 200ms to get data from the database, and .01ms in str_replace calls, then the speedups of going to strtr, or of using echo instead of print are so small as to be irrelevant.

    The dream of being able to use strtr instead of str_replace and get noticeable, measurable speedups is a fantasy.

    0 讨论(0)
  • 2020-12-24 08:03

    Usually pre-mature optimization is a veeeery bad idea. It really doesn't matter when you make your code run 0.5ms faster when single SQL query takes 80ms.

    You should profile code and focus on bottle necks and then try things like caching (static, APC, Memcached). Microoptimizations are the very last step when you've got perfect application design and still need more performance from certain modules/functions.

    0 讨论(0)
  • 2020-12-24 08:06

    This one might seem a bit extreme but...

    PHP is extremely slow. This is undeniable. It is one of the slowest languages out there. If you really want maximum performance I'm going to stay stop right here and use another language.

    Chances are you don't need maximum performance as computers tend to be pretty powerful today and scaling or caching is an option. PHP also tends to become faster with new releases, especially PHP 7 so stating recent will likely give you free performance improvements. Differences between versions may make some micro optimizations pointless.

    Completely contrary to the statement about PHP being the slowest language around, you may find that in some cases it beats nearly every interpreted language out there. This is because PHP originally was meant as a very simple a wrapper for C and many of your PHP functions wrap C functions which makes them quite fast. This actually tends to be the case with most interpreted languages but it is far more noticeable in PHP.

    Contrary to that again some of in built functions may have performance issues where they try to do too much or aren't implemented well. I think until PHP 7 array_unique had been implemented in a very strange and excessively complex way where it would be quicker to use something such as array_flip and array_keys instead.

    PHP is like that. It's one of the most outrageous languages out there as one with a collection of contradictory attributes that are extreme opposites. It's one of the most inconsistent yet the among the easiest to learn. PHP is one of the worst languages out there having grown organically more so than adhering to a design yet it it one of the most productive languages as a DSL for web development. PHP is very bad at scaling yet one of the most scalable web languages out there when run under Apache. I could go on but the point is to expect confusion when it comes to PHP.

    Ditching PHP is not without a cost. Productivity in PHP tends to be much higher than in other languages for webdev and the bar for entry is very low.

    If you want to have the best of both worlds then simply make your PHP code as simple as possible with the goal primarily of it working than it being fast. The next step after this is to make sure you keep good logs so that you can find the requests that have the highest latency or take the most resources. Once you know this you can to targeted profiling. Think of it like this, your logs will tell you what file or request to profile, your profiling will tell you which lines or blocks of code are slow.

    Don't forget though that it's often not PHP that's slow or hard to scale but other resources your PHP scripts depend on such as database.

    General resource monitoring is also useful. For example if your ambient CPU usage is less than 5% why do anything unless latency crops up somewhere? This also helps to give you more hints about where PHP is stalling (where the bottlenecks are, network, HDD IO, memory, CPU, etc). Also keep in mind that today hardware is really really cheap and throwing hardware at problems may turn out much more effective. Such monitoring again allows a targeted approach. I'm an oldie with experience of limited hardware and I can tell you back in the day I used to prematurely optimize a lot. This would give a good return but today it just does not. Typically I can spend a month optimizing something and for the same cost of manhours buy some hardware that might result in a two times performance increase without the big effort. I would not take this too far, hardware does not solve everything but look at it like this, no matter how much you try to optimize there are hard limits presented by hardware so if you go too far in trying to make it work with poor hardware you will quickly hit the realm of diminishing returns.

    Once your find these problem areas you can then attempt to optimize them with better PHP or caching. In most cases this might be enough. Often you may find PHP is not the bottleneck but something else such as database access.

    If you find that you cannot optimize in PHP or with caching you have to think of something else. Using another language is an option and of course here comes the possibility of using C and then wrapping it in PHP as an extension. C is expensive to write in general so this approach lets you use it only where you need it or rather where you receive the most benefit. This is called hotspot optimisation.

    Outside of this there are many other alternatives and you need not wrap only C but if PHP can't do it, PHP can't do it. You can also consider scaling across multiple nodes or processes but keep in mind that in some cases PHP does not scale well when it comes to parallel processing due shared nothing (not many scaling loads need to share for a benefit).

    Whatever you decide, when it comes down to it, we can give 1000 tips about micro-optimisation. Perhaps one of the best all round ones I can give you it to try to put as much into as few PHP native functions as possible because these will run bulk operations in C much faster. You should also follow good theoretical concepts when it comes to algorithm design about things such as time complexity because these are universally applicable. In fact, the majority of performance tips people can give you are probably going to be general programming concepts and not specific to PHP. I would also suggest avoiding library bloat or bulky frameworks. The more they promise the more likely it is to be too good to be true in the real world. Simplicity is key and while libraries are always good think first, are you including ten thousand lines of code to save you writing ten lines out of a hundred which you could turn into a function and reuse yourself.

    Using Opcache or APC if using versions of PHP below 5.5 will instantly give a good speed improvement on PHP parse times and make this a non-concern. PHP 5.5 should have it built in but make sure it's enabled.

    The topic of what is faster than what in what situation pits thousands of things against thousands of things so your best bet is to study and learn more about what PHP actually is, how it works, and how to measure, test and analyse performance. If you have a good sense of how PHP works under the hood you'll be able to better intuit problems when they do arise. Optimizing ten lines of code can become a 10000 word debate. Imagine your application when it has thousands of lines of code.

    I do understand in a few cases the importance or benefit of pre-emptive and micro optimization (largely consists of avoiding performance quirks in languages where performance is disproportionately reduced). However in reality it is usually next to impossible to achieve the kind of gains you expect (again though I have to say the biggest impact you can have if you really care about performance is to ditch PHP altogether, basically this can be seen like asking how can I make a snail fast, the answer is if speed it so important use something built for that). Even the experienced and knowledgeable can have a hard time with this. Almost no one gets it right first time. So where you really want to spend efforts on is maintainability. Keep your code consistent, tidy and well organised. Used VCS to be able to easily delete things (don't comment out code or rename files to .old). Make sure you stay DRY and in general follow good practices. TIAS, Google, etc.

    0 讨论(0)
  • 2020-12-24 08:10

    PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL

    And that's the most important tip you need. If some day you have a real performance problem, profile your application, detect the compromised areas, and came here to ask again :)

    0 讨论(0)
  • 2020-12-24 08:11

    This question (and the answers) are rather dated however it came up high in the listings when I googled for 'PHP performance'.

    While jgmjgm makes some good points, the execution time of PHP is typically a tiny proportion of the time a user spends waiting for a page to appear, but explaining why, let alone detailing the remedies would take far too long here.

    The first step is to identify the things which are taking the most time - and for a web based application you should start at the browser. Google Chrome has a good profiler and for Firefox, there is the Firebug extension. If the slow bit is PHP then dig further with a profiler such as xdebug, but remember that this will encompass any database and file IO.

    0 讨论(0)
  • 2020-12-24 08:13
    1. Please consider binding variables to database's statament instead of putting them into a SQL clause. The same method is similar for the Oracle RDBMS and the MySQL, maybe others too (parse, bind, execute).A query with bound variables is faster prepared for running them more than once.
    2. If you have more than one row to insert, you may use one bulk DML.
    0 讨论(0)
提交回复
热议问题