Does anyone have an idea which would be better for potential string replacement?
If I have a collection of varying length of strings of varying lengths in which some strings might need special replacement of encoded hex values (e.g. =0A, %20… etc)
The “replacements” (there could be multiple) for each string would be handled by a Regular Expression to detect the appropriate escaped hex values
Which would be more efficient?
-
To simply run the replacement on every string in the collection ensuring by brute force that all needed replacements are done
-
To perform a test if a replacement is needed and only run the replacement on the strings that need it.
I’m working in C#.
Update
A little additional info from the answers and comments.
This is primarily for VCARD processing that is loaded from a QR Code
I currently have a regex that uses capture groups to get the KEY, PARAMETERS and VALUE from each KEY;PARAMETERS:VALUE in the VCARD.
Since i’m supporting v 2.1 and 3.0 the encoding and line folding are VERY different so I need to know the version before I decode.
Now it doesn’t make sense to me to run the entire regular expression JUST to get the version and apply the approptiate replace to the whole vcard block of text and THEN rerun the regular expression.
To me it makes more sense to just get my capture groups loaded up then snag the version and do the appropriate decoding replacement on each match
When you just Replace it will perform slightly slower when there’s No Match because of the additional checks that Replace does (e.g.)
Regex.Replace does return the input if no matches are found so there’s no memory issue here.
When there is a match the regex.Match fires twice once when you do it and again when replace does it. Which means Check and Replace will perform slower then.
So your results will be based on
Regex.Matchwill run twice overwelm the extra parameter checks? My guess is it probably will.