The following code shows three different interception methods. The first two methods are faster than the interviewer said, and they are not in the same magnitude.
Byte operations are a little slower than character-based operations because the new String is the final requirement for byte operations. We can see from the source code that it will cause re-encoding by character set.
It can be seen that the fundamental means for a fast string operation is to operate in the form of JAVA characters (char), followed by the form of bytes, and interoperability between bytes and strings is the worst performance.
String subStringInChars (String src, length, String charset) srcLength = I = 0 len = 0 rollback = 0 (len> = length | length> = (src. charAt (I) <256 = 0 + = 1 = 1 + = 2 + = 1 (len! =-= Src. substring (0 String subStringInBytes (String src, length, String charset) (charset = "GBK" firstStartScope = 129-1 firstends1_= 254 + 1 secondStartScope = 64-1 secondends1_= 254 + 1 [] bytes = I = 0 (I <b1 = bytes [I] & 0xFF b2 = bytes [I + 1] & 0xFF (b1> firstStartScope & b1 <firstendsscope & b2> secondStartScope & b2 <(I + 1 = = length-1 (I + 1> = + = 2 + = 1 (I = String (bytes, 0 String s Ubstringings (String str, subSLength, String charset) (charset = "GBK" (str = "" tempSubLength = subSLength; strLength = str. substring (0, strLength <subSLength? StrLength: subSLength); subStrByetsL = subStr. getBytes (charset). length; (subStrByetsL> subSLengthTemp = -- = str. substring (0, subSLengthTemp> strLength? = Random random = String getRandomString (strLength = (strLength <randomLength/2 = [] chars = (I = 0; I <chars. length; I ++ (random. nextInt (3)> 0 = () random. nextInt (Byte. MAX_VALUE) ;}= () (0x4e00 + () (Math. random () * (0x9fa5-0x4e00 + 1 main (String [] args) start = s1 = 0 s2 = 0 s3 = 0 = randomLength = 10000 (I = 0; I <100; I ++ = (str. length () = 0 randomLeng = subStringInBytes (str, randomLen G, s1 + = (System. currentTimeMillis ()-= substringings (str, randomLeng, s2 + = (System. currentTimeMillis ()-= subStringInChars (str, randomLeng, s3 + = (System. currentTimeMillis ()-(! Str1.equals (str2) |! Str2.equals (str3) |! "Byte truncation:" + "string truncation:" + "character truncation:" +
A total of 100 executions, each with at least 5000 characters, no more than 1 W.
The result shows everything (Intel Core E5700 + 4G ):
Byte truncation: 15
String truncation: 5110
Character truncation: 0