开发者

Better ways to replace text - performance

开发者 https://www.devze.com 2023-03-15 16:09 出处:网络
Are there better more performant ways to replace text then using the regex code below, specially if text is large and constantly accessed by different users. I understand performance gains may be negl

Are there better more performant ways to replace text then using the regex code below, specially if text is large and constantly accessed by different users. I understand performance gains may be negligible, but i'm wondering if there are better way to do it. This is what i use to replace foo with foonew

str.repla开发者_如何学运维ce(/foo/gi, 'foonew')

Update: Text data gets retrieved from database into a textarea holder before doing word replacement. I then access textarea value, replace the words, then append updated text to body


Well, patric dw's comment is probably the right answer here. But let's suppose for the sake of argument that you really had to replace a random substring in some larger string, and there was no simple trick to avoid it. Here are three possibilities:

  1. If you are replacing a string with one of smaller length, then you can just shift the characters to the right over it to make up the difference. This avoids reallocating the string.

  2. If the replacement is the same size, you can just do it in place with no copying.

  3. Finally, if it is larger, you can do the string replacement lazily. Just store an object with the string you are substituting and the start/end of the segment that was replaced. This way you can avoid copying. Of course this is much more complicated than just doing the string replacement by hand, so I would probably avoid it unless the performance considerations were really dire.


Text data gets retrieved from database into a textarea holder before doing word replacement. I then access textarea value, replace the words, then append updated text to body.

The most effiecient (and most secure) way to do this is to replace the words, server-side, before ever sending the data.

Then your JS (which the user can modify!) has to do nothing but display the information.

Depending on traffic/volume, it may pay to even have sanitized versions of the text, stored in the database.

0

精彩评论

暂无评论...
验证码 换一张
取 消