Created
May 20, 2013 00:08
-
-
Save komiya-atsushi/5609655 to your computer and use it in GitHub Desktop.
String#split() と Pattern#split() の性能を比較するデモコード。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package biz.k11i.demo; | |
import java.lang.management.GarbageCollectorMXBean; | |
import java.lang.management.ManagementFactory; | |
import java.util.List; | |
import java.util.regex.Pattern; | |
public class StringSplitDemo { | |
public static void main(String[] args) { | |
if (args.length < 2) { | |
return; | |
} | |
final int LOOP_COUNT = 1000 * 1000 * 20; | |
String text = "The quick brown fox jumps over the lazy dog."; | |
String[] patterns = { " ", "\\s", "[ \\t\\n\\x0B\\f\\r]", " |\\t|\\n|\\x0B|\\f|\\r" }; | |
String pattern = patterns[Integer.valueOf(args[1])]; | |
if ("string".equals(args[0])) { | |
profileStringSplit(text, pattern, LOOP_COUNT); | |
} else { | |
profilePatternSplit(text, pattern, LOOP_COUNT); | |
} | |
List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans(); | |
for (GarbageCollectorMXBean b : beans) { | |
if ("PS Scavenge".equals(b.getName())) { | |
System.out.println(String.format("%s\t%s", b.getName(),b.getCollectionCount())); | |
} | |
} | |
} | |
public static void profileStringSplit(String text, String pattern, int loopCount) { | |
long begin, end; | |
begin = System.currentTimeMillis() + 1000; | |
while (System.currentTimeMillis() < begin) { | |
// do nothing | |
} | |
for (int i = 0; i < loopCount; i++) { | |
text.split(pattern); | |
} | |
end = System.currentTimeMillis(); | |
System.out.println(String.format("text : %s, pattern : \"%s\"", text, pattern)); | |
System.out.println(String.format("String#split()\t%d", end - begin)); | |
System.out.println(); | |
} | |
public static void profilePatternSplit(String text, String pattern, int loopCount) { | |
long begin, end; | |
begin = System.currentTimeMillis() + 1000; | |
while (System.currentTimeMillis() < begin) { | |
// do nothing | |
} | |
Pattern p = Pattern.compile(pattern); | |
for (int i = 0; i < loopCount; i++) { | |
p.split(text); | |
} | |
end = System.currentTimeMillis(); | |
System.out.println(String.format("text : %s, pattern : \"%s\"", text, pattern)); | |
System.out.println(String.format("Pattern#split()\t%d", end - begin)); | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment