regex - About regexp performancing -


given string ab

given regex pattern

(a)(b) 

if need remove full string, print second group, can write 2 variant:

1) preg_replace("#(a)(b)#", "$2", "ab") // save both group

and so:

2) preg_replace("#(?:a)(b)#", "$1", "ab") // dont save first group

what variant better performance?

i ran each operation in tight loop 5,000,000 each , compared times. compared 4 operations:

preg_replace("#(a)(b)#", "$2", "ab"); preg_replace("#(?:a)(b)#", "$2", "ab"); preg_replace("#a(b)#", "$2", "ab"); preg_replace("#a(?=b)#", "", "ab"); 

i didn't see consistent difference in times, think doesn't matter performance, i.e. choose whichever makes sense design / semantic perspective.

#1 , #2 performed same. #2 seems faster, occassionally slower (probably due server noise). #3 consistently 5% faster that, , option #4 2% faster #3 (i.e. seems best, because doesn't have capture or interpolate anything).

still, i'd go makes sense.

i realize str_replace("ab", "b", "ab"); may not analogous, use if can. it's consistently more twice fast of others.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -