What are some good PHP performance tips?

前端 未结 13 1772
挽巷
挽巷 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:14

    Lets imagine you have an array of words.
    Like this: $words=array('banana','cat','tuna','bicycle','kitten','caffeine');

    And then you have a search term to find, like this: $find='ca';

    And you want to know all the elements that start with that given term.

    We would usually do like this:

    foreach($words as &$word)if(preg_match('@^'.$find.'@',$word))echo $word,'
    ';

    Or the fastest way:

    foreach($words as &$word)if(strpos($find,$word)==0)echo $word,'
    ';

    But why don't we just do like this:

    foreach($words as &$word)if($find==($find&$word))echo $word,'
    ';

    You shave off a few bytes AND it is faster 'cause you don't have to waste time calling functions.

提交回复
热议问题