アットウィキロゴ

test2

package test.encode;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;

public class TestEncode {
    static CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder()
            .onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);
    static Charset charset = Charset.forName("US-ASCII");
    
    public static void main(String[] args) throws UnsupportedEncodingException {
        int n = 1000000;
        for (int i = 0; i < 100; i++) {
            f0(n);
            f1(n);
            f2(n);
            f3(n);
        }
    }
    
    static void f0(int n) {
        long s1 = System.nanoTime();
        for (int i = 0; i < n; i++) {
            String.valueOf(i);
        }
        long e1 = System.nanoTime();
        
        System.out.println("f0:" + 0.000001*(e1-s1));
    }
    
    static void f1(int n) {
        long s1 = System.nanoTime();
        for (int i = 0; i < n; i++) {
            encodeString(encoder, String.valueOf(i));
        }
        long e1 = System.nanoTime();
        
        System.out.println("f1:" + 0.000001*(e1-s1));
    }
    
    static void f2(int n) throws UnsupportedEncodingException {
        long s2 = System.nanoTime();
        for (int i = 0; i < n; i++) {
            String.valueOf(i).getBytes("US-ASCII");
        }
        long e2 = System.nanoTime();
        
        System.out.println("f2:" + 0.000001*(e2-s2));
    }

    static void f3(int n) {
        long s2 = System.nanoTime();
        for (int i = 0; i < n; i++) {
            String.valueOf(i).getBytes(charset);
        }
        long e2 = System.nanoTime();
        
        System.out.println("f3:" + 0.000001*(e2-s2));
    }
    
    public static byte[] encodeString(CharsetEncoder encoder, String src) {
        ByteBuffer buf = null;
        try {
            CharBuffer cb = CharBuffer.wrap(src);
            buf = encoder.encode(cb);            
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }
        return buf.array();
    }

}
最終更新:2014年08月23日 22:54