JSP - htmlspecialchars() htmlentities() PHP like function - version 2.0

The search has continued and no solution has been found yet.

As I was not pleased with the performance of my previous approach I worked out the following one:

  
StringBuffer sb = new StringBuffer();
for(int i=0; i<content.length(); i++) {
  char c = content.charAt(i);

  switch (c) {
    case ‘<’ :
      sb.append(”&lt;”);
      break;
    case ‘>’ :
      sb.append(”&gt;”);
      break;

    case ‘&’ :
      sb.append(”&amp;”);
      break;
    case ‘”‘ :
      sb.append(”&quot;”);
      break;
    case ‘\” :

      sb.append(”&apos;”);
      break;
    default:
      sb.append(c);
    }
}
  
content = sb.toString();

This verision is a lot faster then the previous one. On the page source from the slashdot site this version performed in under 8ms while the other one had it’s best performance in 20ms (usually in the range of 30ms).

1 comment so far

  1. Esteban Trujillo January 23, 2008 5:43 am

    thanks, the code is great!

Leave a comment

Please be polite and on topic. Your e-mail will never be published.