1

I'm looking for a more efficient code solution (in PHP) for the code bellow. This code is called a lot of times and has been pointed by webgrind as the source of bad performance. (Comparing with all the other components of my code).

$xName = "com.company.product";
$xApp = explode(".", $xName);
$xApp = end($xApp);
$xApp = strtoupper($xApp);

Example Input: com.company.product Example Output: PRODUCT

How should I re-code this to have the same output and be faster? Thank you.

4
  • 1
    Out of those 4 lines whats the profile distribution? Commented Dec 27, 2013 at 21:05
  • @MikeB 6 milliseconds to process a request and those 4 lines are into a function that appears at the top of self cost. Commented Dec 27, 2013 at 21:09
  • I meant what's the % cost across those lines? Which one takes the most time compared to the others? i.e. explode() takes 50% while end and strtoupper are closer to 25 each. Commented Dec 27, 2013 at 21:10
  • @MikeB explode() was definitely the source of the problem. This is fixed now using Jasper solution but thanks anyway ;) Commented Dec 27, 2013 at 21:29

1 Answer 1

2

I'm not really sure of the performance difference but you can use strrpos to get the position of the last period and then use substr to get everything after that position:

$xName  = "com.company.product";
$dotPos = strrpos($xName, ".");
$xApp   = strtoupper(substr($xName, $dotPos + 1));

I'd imagine this is quicker than exploding a string.

Here's the PHP documentation for strrpos: http://www.php.net/strrpos

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I completely forgot about that one ;) I'll test that one in production for the next hours and check the performance.
@TCB13 I'll be interested to see the performance difference, better or worse. If you can, please report back what you find.
I just tested this with 10000000 iterations (with the same $xName). This one took 10.53 seconds, while the original version took 16.78 seconds. Clearly, this is faster.
@Jasper your solution is clearly faster, I just tried to process stored records in a DB and I got similar results as Amal Murali . Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.