title: Performance intensive string splitting and manipulation in java
body: <p>What is the most efficient way to split a string by a very simple separator?</p>
  
  <p>Some background:</p>
  
  <p>I am porting a function I wrote in C with a bunch of pointer arithmetic to java and it is incredibly slow(After some optimisation still 5* slower).
  Having profiled it, it turns out a lot of that overhead is in String.split</p>
  
  <p>The function in question takes a host name or ip address and makes it generic:</p>
  
  <p>123.123.123.123->*.123.123.123</p>
  
  <p>a.b.c.example.com->*.example.com</p>
  
  <p>This can be run over several million items on a regular basis, so performance is an issue.</p>
  
  <p>Edit: the rules for converting are thus:</p>
  
  <ul>
  <li>If it's an ip address, replace the first part</li>
  <li>Otherwise, find the main domain name, and make the preceding part generic. </li>
  </ul>
  
  <p>foo.bar.com-> *.bar.com
  foo.bar.co.uk-> *.bar.co.uk</p>
  
  <p>I have now rewritten using lastIndexOf and substring to work myself in from the back and the performance has improved by leaps and bounds. </p>
  
  <p>I'll leave the question open for another 24 hours before settling on the best answer for future reference</p>
  
  <p>Here's what I've come up with now(the ip part is an insignificant check before calling this function)</p>
  
  <pre><code>private static String hostConvert(String in) {
      final String [] subs = { "ac", "co", "com", "or", "org", "ne", "net", "ad", "gov", "ed" };
  
      int dotPos = in.lastIndexOf('.');
      if(dotPos == -1)
          return in;
      int prevDotPos = in.lastIndexOf('.', dotPos-1);
      if(prevDotPos == -1)
          return in;
      CharSequence cs = in.subSequence(prevDotPos+1, dotPos);
      for(String cur : subs) {
          if(cur.contentEquals(cs)) {
              int start = in.lastIndexOf('.', prevDotPos-1);
              if(start == -1 || start == 0)
                  return in;
              return "*" + in.substring(start);
          }
      }
  
      return "*" + in.substring(prevDotPos);
  }
  </code></pre>
  
  <p>If there's any space for further improvement it would be good to hear.</p>