, ". The usual practice is to use several replace functions in succession, but Clear only uses one replace to complete the replacement."/> , ". The usual practice is to use several replace functions in succession, but Clear only uses one replace to complete the replacement.">
Home >Web Front-end >JS Tutorial >Benchmark of efficient Javscript string replacement function
This is a frequently used HTML special character replacement function, that is, replacing &, <, >, " and other functions with &, <, >, ". The usual practice is to use several replace functions in succession, but Clear only uses one replace to complete the replacement.
I benchmarked these two functions and found that the efficiency of the new function is about 1.4 times that of the original function. Although it is not as efficient as expected, when there are more strings to be replaced, the efficiency should improve.
The test method is to execute two functions 100 times on a 2048-byte long string, and take the execution time. Below are the results of 10 tests. toTXT_1 is the usual method, and toTXT_2 is the Clear method.
toTXT_1(ms) | toTXT_2(ms) | toTXT_1/toTXT_2 |
1609 | 1204 | 75% |
2250 | 1547 | 69% |
1672 | 1313 | 79% |
1813 | 1250 | 69% |
1844 | 1219 | 66% |
2063 | 1421 | 69% |
2031 | 1172 | 58% |
1797 | 1360 | 76% |
2015 | 1281 | 64% |
1860 | 1500 | 81% |
The above is the content of the benchmark of the efficient Javscript string replacement function. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!