ling
ling

Reputation: 10037

php regex check first char optimization

I heard that regex are slow. So I wondered which code would be more efficient, given that the pattern I'm looking for starts with an arobase:

This one ?

if(preg_match('!^@([a-zA-Z0-9_]+):([a-zA-Z0-9]+)$!', $subject, $match)){
    // do something
}

Or this one ?

if(
    '@' === substr($subject, 0, 1) && 
    preg_match('!^@([a-zA-Z0-9_]+):([a-zA-Z0-9]+)$!', $subject, $match)
){
    // do something
}

I guess I will run some custom tests...

Upvotes: 0

Views: 45

Answers (1)

deep
deep

Reputation: 106

This is bad optimization. Better if u will use profiler and optimise only code that need to be optimised.

But this code can be optimised by string array access trick.

if('@' === $subject[0] && preg_match('!^@([a-zA-Z0-9_]+):([a-zA-Z0-9]+)$!', $subject, $match)){
    // do something
}

Upvotes: 1

Related Questions