devdaily home | java | perl | unix | directory | weblog

up previous next
Next: Other tricks and black Up: Optimizing your first project Previous: The third run -

Getting harder now

Once again I find myself staring down the barrel of some code that I didn't write. Now I've hit something that might be a real problem. My best hope now is to change the order of the code in the highlighted method, and try to delay the calling of the compile() and matches() methods until it's absolutely necessary. I'm hoping that by calling the indexOf() method first, it will get enough hits that the compile() and matches() methods aren't called very frequently.

I also try moving the Pattern and Matcher constructors out of the while loop. To summarize the changes, my code started off like this:

 while ( it.hasNext() )
 {
   String keywordToReject = ((String)it.next()).toLowerCase();

   if ( subjectField.indexOf(keywordToReject)>=0 )
   {
     markMessageAsRejected(emailMessage, "Subject field matched a keyword.");
     return;
   }

   Pattern aPattern = Pattern.compile(keywordToReject,
                                      Pattern.CASE_INSENSITIVE);
   Matcher aMatcher = aPattern.matcher(subjectField);

   if ( (subjectField.indexOf(keywordToReject)>=0) || aMatcher.matches() )
   {
     markMessageAsRejected(emailMessage, "Subject field matched a keyword.");
     return;
   }

and then I changed it to look like this:

 Pattern aPattern = null;
 Matcher aMatcher = null;
 while ( it.hasNext() )
 {
   String keywordToReject = ((String)it.next()).toLowerCase();

   if ( subjectField.indexOf(keywordToReject)>=0 )
   {
     markMessageAsRejected(emailMessage, "Subject field matched a keyword.");
     return;
   }

   aPattern = Pattern.compile(keywordToReject,Pattern.CASE_INSENSITIVE);
   aMatcher = aPattern.matcher(subjectField);

   if ( aMatcher.matches() )  // faster
   {
     markMessageAsRejected(emailMessage, "Subject field matched a keyword.");
     return;
   }

These were total guesses on my part, but I was a little desperate. To my surprise I again reduced the run time, this time down to 9,353 ms. As much as these were guesses on my part, I couldn't have begun to make these ``educated'' guesses without Optimizeit.


up previous next
Next: Other tricks and black Up: Optimizing your first project Previous: The third run -