Java escape HTML - string replace slow?

后端 未结 8 578
长情又很酷
长情又很酷 2021-01-22 17:34

I have a Java application that makes heavy use of a large file, to read, process and give through to SolrEmbeddedServer (http://lucene.apache.org/solr/).

One of the func

相关标签:
8条回答
  • 2021-01-22 17:53

    For html escaping you can use StringEscapeUtils.escapeHtml(input) from commons-lang. It is supposedly implemented in a more efficient way there.

    0 讨论(0)
  • 2021-01-22 17:53

    This is certainly not the most efficient way to do a lot of replacements. Since strings are immutable, each .replace() leads to the construction of a new String object. For the example you give, each call to this function leads to the temporary creation of 6 String objects.

    Considering the example you give, the simplest solution is to use an existing library function for HTML entity encoding. Apache commons StringEscapeUtils is one option. Another one is HTMLEntities

    0 讨论(0)
  • 2021-01-22 17:57

    The general algorithm for String.replace is a little complicated, but it shouldn't be that bad. Looking at the code, it is in fact implemented using regex so wont be fast - ick.

    Obviously, you can write much faster code by iterating through character by character. Possibly working out the exact length first.

    You might want to consider how characters outside of[ -~] are handled. You might also want to use a library which has already implemented the functionality.

    0 讨论(0)
  • 2021-01-22 18:03

    Your approach with multiple replace methods could be slow.

    Look at Apache Commons Lang's StringEscapeUtils for a speedy implementation of escaping HTML entities.

    0 讨论(0)
  • 2021-01-22 18:09

    For the casual reader, there is a new player in the Html escape field: unbescape.

    An unescape operation on HTML code can be done like this:

    final String unescapedText = HtmlEscape.unescapeHtml(escapedText); 
    
    0 讨论(0)
  • 2021-01-22 18:12

    Apache Commons Lang has a very efficient escapeHtml method in its StringEscapeUtils class.

    It's fairly smart about it, and doesn't use string replacement in the way you describe, but instead iterates through the characters, replacing characters with appropriate entities as it finds them.

    I don't have any benchmarks handy, but if this stuff is on the critical path of your code, you would be wiese to use this off-the-shelf, faster solution.

    0 讨论(0)
提交回复
热议问题