Forum Moderators: coopster & phranque

Message Too Old, No Replies

Which option do you think would be faster?

Only one server, live, so no way to reliably benchmark

         

csdude55

1:22 pm on Oct 11, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've been using this code for awhile to shorten URLs that are posted by users:

if (length($_) > 45) {
# converts this:
# https://www.example.com/whatever.html?something=abc
# to this
# https://www.example.com/wha...ething=abc
$_ = substr($_, 0, 27) . '...' . substr($_, -10);
}


I already check to make sure that it's a proper link before this, so there's no real need to check it here. It has 3 built-in commands: length(), and then two iterations of substr().

As an alternative, I COULD do:

# reads as, find exactly 27 characters, followed by 5 or more characters,
# followed by exactly 10 characters, then replace the 5 or more with ...
s#([^\s]{27})[^\s]{5,}([^\s]{10})#$1...$2#i;


This variation is a regex, which is traditionally slower, but is it slower than 3 commands combined?

Of course, I know that we're probably talking microseconds here. But this is really just for my own education. Over the years I've followed the "use regex only as a last resort" guideline, but I recently realized in PHP testing that sometimes it's faster than using multiple built-in commands. So while I'm rebuilding anyway, why not shave microseconds where I can?

JorgeV

5:51 pm on Oct 11, 2019 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



Hello-

Whatever is the more convenient for you, and/or making your code the easier to understand.

Short string manipulations will not even make microseconds of difference :). This would be different if you were doing the same on a long text, this is where regex are get slower.