The fastest way to convert case in Java

package io.mycat;

import java.util.stream.IntStream;
/**
 * 'a'=97 for lowercase letters, A=65 for uppercase letters, and a difference of 32 is better. Use this difference to convert between upper and lower case
 * @author : Hpgary
 * @date : May 3, 2017 10:26:26
 * @mail: [email protected]
 * */
public class StringUtils {

	protected final static byte[] CHAR_TYPE = new byte[512];

	protected final static byte CHARACTER_DIFFER = 32;

	static {
		/**
		 * Put uppercase letters into CHAR_TYPE first, convert uppercase to lowercase
		 * */
		IntStream.rangeClosed('A', 'Z').forEach(c -> CHAR_TYPE[c] = (byte) (c + CHARACTER_DIFFER));
		/**
		 * Put lowercase letters into CHAR_TYPE, the stored value is lowercase letters
		 * */
		IntStream.rangeClosed('a', 'z').forEach(c -> CHAR_TYPE[c] = (byte) (c));
	}
	
	public static byte[] toUpperCase(String src) {
		byte[] bytes = src.getBytes();
		for (int x = 0; x < bytes.length; x++) {
			int tmpLen = bytes[x] << 1;
			if (tmpLen < CHAR_TYPE.length && tmpLen >= 0) {
				byte b = CHAR_TYPE[bytes[x]];
				if (b != 0) {
					bytes[x] = (byte) (b - CHARACTER_DIFFER);
				}
			}
		}
		return bytes;
	}

	public static byte[] toLowerCase(String src) {
		byte[] bytes = src.getBytes();
		for (int x = 0; x < bytes.length; x++) {
			int tmpLen = bytes[x] << 1;
			if (tmpLen < CHAR_TYPE.length && tmpLen >= 0) {
				byte b = CHAR_TYPE[bytes[x]];
				if (b != 0) {
					bytes[x] = b;
				}
			}
		}
		return bytes;
	}

	public static void main(String[] args) {
		int count = 100000 ;
		String str = "fdajfadSKfj1221SDKfdasfdsafjdsafjlsadjfkl;sdajflksadjlfkjasdlk;fjasdklfasdA" ;
		
		long time2 = System.currentTimeMillis();
		for (int x = 0; x < count; x++) {
			str.toUpperCase();
		}
		System.out.println(System.currentTimeMillis() - time2);  //51 - 53
		
		long time1 = System.currentTimeMillis();
		for (int x = 0; x < count; x++) {
			toUpperCase(str) ;
		}
		System.out.println(System.currentTimeMillis() - time1); // 35-37
	}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326490696&siteId=291194637