1

I need to perform many str_replace($search, $replace, $input) using the same $search and $replace. These are exploded in a function:

function sr($input) {

    $search = explode(",","s1,s2,s3,....");
    $replace = explode(",","r1,r2,r3,...");

    return str_replace($search, $replace, $input);

}

It is not very efficient. From another SO question, I see that I could create constant arrays, but the suggested method implies serialization. I bet this is not efficient too, but am I right?

I have a compiled language mindset, so whenever I can make something constant, I am happy. But does it make sense in PHP? I am not a PHP pro.

More precisely, knowing that this function is going to be used when users make web requests to a page, how can I optimize explodes efficiently? Is there any such thing as precompiled code in PHP? Or can I define constant arrays once for all, efficiently (like testing whether the constant is already created/available in the context)?

UPDATE

Taking Truth's suggestion into account, we can modify the function as following:

function sr($input) {

    $search = array("s1","s2","s3",....");
    $replace = array("r1","r2","r3",...");

    return str_replace($search, $replace, $input);

}

The remaining question is: is it optimal to declare these arrays at each call or could should we try to create them as constants in the context?

Community
  • 1
  • 1
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

1 Answers1

10

Does it make sense to [take random action right off your head] to increase performance?

No.

  1. Start worrying about performance only if you have certain performance problem.
  2. Once you've got it - start profiling.
  3. Once you've got certain profiling results pointing to certain bottleneck - start optimizing that bottleneck.
  4. Repeat until done.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345