Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.regex.Pattern;
- public class Main {
- public static void main(String[] args) throws Exception {
- String s = "(Yeahhhh) I have finally made it to the (top)";
- {
- long chars = 0;
- Pattern p = Pattern.compile("[()]");
- // warmup
- chars += lengthReplaceAll(s, p);
- long start = System.currentTimeMillis();
- for (int i = 0; i < 10000000; i++) {
- chars += lengthReplaceAll(s, p);
- }
- System.out.println(System.currentTimeMillis() - start + "ms");
- System.out.println(chars);
- }
- {
- long chars = 0;
- // warmup
- chars += lengthCharAt(s);
- long start = System.currentTimeMillis();
- for (int i = 0; i < 10000000; i++) {
- chars += lengthCharAt(s);
- }
- System.out.println(System.currentTimeMillis() - start + "ms");
- System.out.println(chars);
- }
- {
- long chars = 0;
- // warmup
- chars += lengthCharAt2(s);
- long start = System.currentTimeMillis();
- for (int i = 0; i < 10000000; i++) {
- chars += lengthCharAt2(s);
- }
- System.out.println(System.currentTimeMillis() - start + "ms");
- System.out.println(chars);
- }
- }
- private static int lengthReplaceAll(String s, Pattern p) {
- return s.length() - p.matcher(s).replaceAll("").length();
- }
- private static int lengthCharAt(String s) {
- int c = 0;
- int l = s.length();
- for (int j = 0; j < l; j++) {
- switch (s.charAt(j)) {
- case '(':
- case ')':
- c++;
- }
- }
- return c;
- }
- /**
- * calling length() every time
- */
- private static int lengthCharAt2(String s) {
- int c = 0;
- for (int j = 0; j < s.length(); j++) {
- switch (s.charAt(j)) {
- case '(':
- case ')':
- c++;
- }
- }
- return c;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement