StringBuilder performance Test in Java _java

Source: Internet
Author: User
Tags string indexof

When looking at the KMP algorithm, you want to simply count the execution time and performance.

The conclusion is that: Java string IndexOf method performance is best, followed by the KMP algorithm, followed by the traditional BF algorithm, of course, a bit far-fetched, the sun's algorithm is also used to achieve the use of Java, the look is not like the KMP, but also need to study in detail.

The test code looks like this:

Package COM.TEST.TEST.KMP;

Import Java.util.Random;
	public class Kmptest {public static void main (string[] args) {test ();
		}//public static void Test () {//int alllen = 8000000;
		int sublen = 11;
		int charlen = 4;
		String cl = buildstring (Charlen);
		int times = 50;
	Testmatch (Alllen, Sublen, cl, times);
		public static void Testmatch (int alllen, int sublen, String cl, int times) {int allbf = 0;
		int allstring = 0;
		int ALLKMP = 0;
		int ALLGC = 0;
		int allbuild = 0;
		
		int alltoarray = 0;
		
		Long start = System.currenttimemillis ();
		System.out.println ("--------------------------");
			for (int i = 0; I < times; i++) {//1. The loss of a constructed string long Buildstart = System.currenttimemillis ();
			String sub = buildstring (Sublen, CL);
			String all = Buildstring (Alllen, sub) +sub;
			Long buildend = System.currenttimemillis ();
			Allbuild + = (Buildend-buildstart); 2.
			Loss of ToCharArray long Toarraystart = System.currenttimemillis (); Char[] ALlarray = All.tochararray ();
			char[] Subarray = Sub.tochararray ();
			Long toarrayend = System.currenttimemillis ();
			Alltoarray + = (Toarrayend-toarraystart);
			Long STARTBF = System.currenttimemillis ();
			int INDEXBF = Bfindexof (all, sub);
			Long endbf = System.currenttimemillis ();
			Long TIMEOUTBF = ENDBF-STARTBF;
			ALLBF + = TIMEOUTBF;
			System.GC ();
	
			ALLGC + = (System.currenttimemillis ()-ENDBF);
			Long startstring = System.currenttimemillis ();
			int indexstring = Stringindexof (all, sub);
			Long endstring = System.currenttimemillis ();
			Long timeoutstring = endstring-startstring;
			Allstring + = timeoutstring;
			System.GC ();
			

			ALLGC + = (System.currenttimemillis ()-endstring);
			Long STARTKMP = System.currenttimemillis ();
			int INDEXKMP = Kmpindexof (all, sub);
			int INDEXKMP = Kmp_index (Allarray, Subarray);
			Long ENDKMP = System.currenttimemillis ();
			Long TIMEOUTKMP = ENDKMP-STARTKMP; ALLKMP + + timeoutkmP
			System.GC ();
			
			ALLGC + = (System.currenttimemillis ()-ENDKMP);
			System.out.println ("all=" +all.substring (0,100) + "...");
			System.out.println ("sub=" +sub);
			System.out.println ("indexbf=" +indexbf+ "; Time consuming:" +timeoutbf+ "MS");
			System.out.println ("indexstring=" +indexstring+ "; Time consuming:" +timeoutstring+ "MS"); if (INDEXBF = = indexstring && INDEXKMP = = indexstring) {//SYSTEM.OUT.PRINTLN ("!!!! The contrast is equal.
			");
			else {throw new RuntimeException ("contrast error.");
				}//if (i% = =) {System.out.println (i+ "secondary bfindexof=" +allbf+ "MS");
				System.out.println (i+ "secondary stringindexof=" +allstring+ "MS");
				System.out.println (i+ "secondary kmpindexof=" +allkmp+ "MS");
				System.out.println (i+ "secondary allbuild=" +allbuild+ "MS");
				System.out.println (i+ "secondary alltoarray=" +alltoarray+ "MS");
				SYSTEM.OUT.PRINTLN (i+ "* 3 times, gc=" +allgc+ "MS");
				Long end = System.currenttimemillis ();
				Long alltime = End-start;
				Long losstime = alltime-(ALLBF+ALLSTRING+ALLKMP+ALLGC);System.out.println (i+ "times, all total time consuming:" + (Alltime) + "MS; Loss:" + losstime + "MS; loss ratio:" + ((0.0+losstime)/alltime * 100) + "%");
			System.out.println ("--------------------------");
		}//System.out.println (times+ "secondary bfindexof; Total time consuming:" +allbf+ "MS");
		System.out.println (times+ "secondary stringindexof; Total time consuming:" +allstring+ "MS");
		System.out.println (times+ "secondary kmpindexof; Total time consuming:" +allkmp+ "MS");
		System.out.println (times+ "secondary allbuild=" +allbuild+ "MS");
		System.out.println (times+ "secondary alltoarray=" +alltoarray+ "MS");
		SYSTEM.OUT.PRINTLN (times+ "* 3 times, GC; Total time consuming:" +allgc+ "MS");
		Long end = System.currenttimemillis ();
		Long alltime = End-start;
		Long losstime = alltime-(ALLBF+ALLSTRING+ALLKMP+ALLGC);
		System.out.println (times+ "times, all total time consuming:" + (Alltime) + "MS; Loss:" + losstime + "MS; loss ratio:" + ((0.0+losstime)/alltime * 100) + "%");
		
	System.out.println ("--------------------------");
	////build character public static String buildstring (int len) {return buildstring (len, null); public static String buildstring (int lEn, String Sub) {//final int type_number = 0;
		final int type_lowercase = 1;
		final int type_uppercase = 2;
		Long seed = System.nanotime ();
		Random Random = new Random (seed);
		StringBuilder builder = new StringBuilder ();
			for (int i = 0; i < len; i++) {//int type = Random.nextint (3);//0-2 int cvalue = 0;  if (Type_number = = type) {Cvalue = ' 0 ' + random.nextint (ten);//0~ (n-1)} else if (type_lowercase = = type) {Cvalue = ' a ' + random.nextint;//0~ (n-1)} else if (type_uppercase = = TYPE) {cvalue = ' a ' + random.nextint (num);//0~ (n -1} else {throw new RuntimeException (Random.class.getName () + "#newxtInt (int);
			Wrong! ");}
			Cvalue = ' A ' + random.nextint ();//0~ (n-1)//char C = (char) cvalue;
				if (null!= sub && sub.length () > 1) {int index = Random.nextint (Sub.length ());
			c = Sub.charat (index);
			}//string s = string.valueof (c);
			Builder.append (c); }//Return builder. toString (); /** * Java self-contained method with internal implementation * @param all * @param sub * @return/public static int Stringindexof (String al
		L, String Sub) {//defensive programming if (null = ALL | | null== sub) {return-1;
	//Call Java String method return All.indexof (sub);
		/** * BF Algorithm * @param all * @param sub * @return/public static int Bfindexof (string all, String sub) {
		Defensive programming if (null = ALL | | null== sub) {return-1;
		}//int lenall = All.length ();
		int lensub = Sub.length ();
		int i = 0;
			while (I < Lenall) {///From I subscript start contrast int j = 0;
				while (J < lensub) {//char all_i = All.charat (i);
				Char Sub_j = Sub.charat (j);
					if (all_i = = Sub_j) {//equality continues to contrast the next character i++; j + +;
				This growth is important} else {//otherwise jump out of inner loop break;
			}//If J grows to equal with lensub, match success if (lensub = = j) {return i-lensub;
	else {i = 1+i-j;//Backtracking I}}//return-1; /** * KMP Algorithm * @param all * @param sub * @rEturn */public static int Kmpindexof (string all, String sub) {//char[] Allarray = All.tochararray (); 
		char[] Subarray = Sub.tochararray ();
	Return Kmp_index (Allarray, Subarray); /** * Gets the next function value of the string * * @param t * String * @return Next function value/public static int[] Next (c 
    Har[] t) {int[] next = new Int[t.length]; 
    Next[0] =-1; 
    int i = 0; 
    Int j =-1; 
        while (I < t.length-1) {if (j = = 1 | | t[i] = = T[j]) {i++; 
        j + +; 
        if (T[i]!= t[j]) {next[i] = j; 
        else {Next[i] = next[j]; 
      } else {j = next[j]; 
  } return to Next; /** * KMP Matching String * * @param allarray * Main String * @param subarray * Mode String * @return if match 
    Success, return subscript, otherwise return-1/public static int Kmp_index (char[] Allarray, char[] subarray) {int[] next = next (Subarray); 
    int i = 0; 
    int j = 0; while (i; = Allarray.length-1 && J <= subarray.length-1) {if (j = = 1 | | allarray[i] = = Subarray[j]) { 
        i++; 
      j + +; 
      else {j = next[j]; 
    } if (J < subarray.length) {return-1; else return i-subarray.length; Returns the header subscript} of the pattern string in the main string

One result of the test is as follows:

--------------------------
10 times bfindexof= 94ms
10 times stringindexof= 56ms
10 times kmpindexof= 76ms
10 times allbuild= 5870ms
10 times alltoarray= 137ms
10*3 times, gc= 155ms
10 times, all total time consuming: 6388ms; loss: 6007ms; loss ratio: 94.03569192235442%
--------------------------
30 times bfindexof= 365ms
30 times stringindexof= 222ms
30 times kmpindexof= 295ms
30 times allbuild= 16452ms
30 times alltoarray= 395ms
30*3 times gc= 452ms
30 times all total time consuming: 18184ms; Loss: 16850ms; Loss ratio: 92.66388033435987%
--------------------------
50 times bfindexof; Total time: 550ms
50 stringindexof; Total time consuming : 335ms
50 times kmpindexof; Total time: 450ms
50 times allbuild= 26501ms
50 times alltoarray= 637ms
50*3 times GC; Total time consuming: 734ms
50 times, all total time consuming: 29211ms; loss: 27142ms; loss ratio: 92.91705179555647%
--------------------------

As you can see, using the StringBuilder construct string, the 8 million * 50 times append consumes about 26 seconds. The conversion is 16 million times per second ...
It seems to be necessary to write a special timing function, and JUnit has its own statistics, but the sample is not very good to do.

Thus, the preparation of the data, which is the key to the selection of test cases, may need to be written into a text file by Mr.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.