When should we use Pattern and Matcher?

Today I came across a question, and the question was:

Suppose I want to find the total number of occurrences of the following substring:

Any substring that starts with 1 followed by any(0 or more) number of 0 
and then followed by 1.

I solved this issue in two ways:

Method 1

I have created a regular expression to him 1[0]*1and used a class Patternand Matcherto solve the problem.

Method 2

I crossed the line and incremented the counter when the pattern was matched.

My question is why my first method is extremely inefficient compared to my second method. I thought inline functions were more efficient to use. It does not blame it in all cases. The time gap is really big.

Here is the proof:

import java.util.regex.*;
class Pat_mat
{
 public static void main(String []args)
 {
     String str="111011010000001011";
     Pattern p=Pattern.compile("10*(?=1)");
     Matcher matcher=p.matcher(str);
     int s=0,i;
     long st=System.nanoTime();
     while(matcher.find())
      ++s;
     long ft=System.nanoTime()-st;      
     System.out.println("time taken by inbuilt fn "+ft);
     System.out.println("output: "+s);
     s=0;i=0;
     st=System.nanoTime();
     while(i<str.length())
     {
         if(str.charAt(i)!='1')
          {++i;continue;}
         else
         {
             if(i+1<str.length()&&str.charAt(i+1)=='1')
              ++s;
             else if(i+1<str.length()&&str.charAt(i+1)=='0')
              {while(i+1<str.length()&&str.charAt(i+1)=='0')
               ++i;               
             if((i+1)<str.length()&&str.charAt(i+1)=='1')
              ++s;}
         }
         ++i;
     }     
     ft=System.nanoTime()-st; 
     System.out.println("time taken by my way "+ft);
     System.out.println("output: "+s);
 }
}
+4

Source: https://habr.com/ru/post/1609322/


All Articles