Path: blob/master/test/jdk/sun/nio/cs/StrCodingBenchmarkUTF8.java
41152 views
/*1* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.util.*;24import java.nio.*;25import java.nio.charset.*;2627public class StrCodingBenchmarkUTF8 {2829public static void main(String[] args) throws Throwable {3031final int itrs = Integer.getInteger("iterations", 100000);32final int size = 2048;33final int subsize = Integer.getInteger("subsize", 128);34final Random rnd = new Random();35final int maxchar = 0x7f;3637Charset charset = Charset.forName("UTF-8");38final String csn = charset.name();39final Charset cs = charset;4041int[] starts = new int[] { 0, 0x80, 0x800, 0x10000};42for (int nb = 1; nb <= 4; nb++) {4344final CharsetEncoder enc = cs.newEncoder();4546char[] cc = new char[size];47int i = 0;48while (i < size - 3) {49i += Character.toChars(starts[nb - 1] + rnd.nextInt(maxchar), cc, i);50}5152final String string = new String(cc);53final byte[] bytes = string.getBytes(cs);5455System.out.printf("%n--------%s[nb=%d]---------%n", csn, nb);56int sz = 12;57while (sz < size) {58System.out.printf(" [len=%d]%n", sz);59final byte[] bs = Arrays.copyOf(bytes, sz);60final String str = new String(bs, csn);61StrCodingBenchmark.Job[] jobs = {62new StrCodingBenchmark.Job("String decode: csn") {63public void work() throws Throwable {64for (int i = 0; i < itrs; i++)65new String(bs, csn);66}},6768new StrCodingBenchmark.Job("String decode: cs") {69public void work() throws Throwable {70for (int i = 0; i < itrs; i++)71new String(bs, cs);72}},7374new StrCodingBenchmark.Job("String encode: csn") {75public void work() throws Throwable {76for (int i = 0; i < itrs; i++)77str.getBytes(csn);78}},7980new StrCodingBenchmark.Job("String encode: cs") {81public void work() throws Throwable {82for (int i = 0; i < itrs; i++)83str.getBytes(cs);84}},85};86StrCodingBenchmark.time(StrCodingBenchmark.filter(null, jobs));87sz <<= 1;88}89}90}91}929394