Is there any recommended way to do multiple string substitutions other than doing 'replace' chaining on a string (i.e. text.replace(a, b).replace(c, d).replace(e, f) ...)? How would you, for example, implement a fast function that behaves like PHP's htmlspecialchars in Python?
I compared (1) multiple 'replace' method, (2) the regular expression method, and (3) Matt Anderson's method.
With n=10 runs, the results came up as follows:
On 100 characters:
TIME: 0 ms [ replace_method(str) ] TIME: 5 ms [ regular_expression_method(str, dict) ] TIME: 1 ms [ matts_multi_replace_method(list, str) ]
On 1000 characters:
TIME: 0 ms [ replace_method(str) ] TIME: 3 ms [ regular_expression_method(str, dict) ] TIME: 2 ms [ matts_multi_replace_method(list, str) ]
On 10000 characters:
TIME: 3 ms [ replace_method(str) ] TIME: 7 ms [ regular_expression_method(str, dict) ] TIME: 5 ms [ matts_multi_replace_method(list, str) ]
On 100000 characters:
TIME: 36 ms [ replace_method(str) ] TIME: 46 ms [ regular_expression_method(str, dict) ] TIME: 39 ms [ matts_multi_replace_method(list, str) ]
On 1000000 characters:
TIME: 318 ms [ replace_method(str) ] TIME: 360 ms [ regular_expression_method(str, dict) ] TIME: 320 ms [ matts_multi_replace_method(list, str) ]
On 3687809 characters:
TIME: 1.277524 sec [ replace_method(str) ] TIME: 1.290590 sec [ regular_expression_method(str, dict) ] TIME: 1.116601 sec [ matts_multi_replace_method(list, str) ]
So kudos to Matt for beating the multi 'replace' method on a fairly large input string.
Anyone got ideas for beating it on a smaller string?