title: Optimization of Regex
body: <p>I am using jprofiler to help me reduce the CPU usage. Here are my two scenarios:</p>
  
  <p>Scenario 1: </p>
  
  <pre><code>//Global Variables
      static Pattern escapeSequences = Pattern.compile("(\\r|\\n|\\t)");
      static Pattern printableCharacters = Pattern.compile("[^\\p{Print}]");
  
       String message = String.format(format, args);
  
  
            return printableCharacters.matcher(escapeSequences.matcher(message).replaceAll("")).replaceAll("?");
  </code></pre>
  
  <p>Scenario 2:</p>
  
  <pre><code>            for (int i=0; i&lt;args.length; ++i) {
                  if (args[i] instanceof String) {
                      args[i].replaceAll("(\\r|\\n|\\t)","").replaceAll("[^\\p{Print}]", "?");
                  }
              }
  
  return formater = String.format(format, args);
  </code></pre>
  
  <p>Scenario 1 runs in approximately 9% while scenario 2 runs in approximately 7%. What i do not understand here is that if the regex is pre-compiled once as opposed to every time, why is the cpu higher? What can I do to reduce the CPU below 7%.</p>