像Guava Splitter一样快速搜索大型CSV

时间:2017-07-09 22:06:38

标签: java stream guava

自从Java 8发布以来,我发现我的项目中不需要超过2 MB的Google Guava,因为我可以用普通的Java替换大部分内容。但是我真的很喜欢漂亮的Splitter API,它同时非常快。最重要的是 - 拉懒惰。它似乎可以用Pattern.splitAsStream替换。所以我准备了快速测试 - 在长字符串的中间找到一个值(即拆分整个字符串没有意义)。

package splitstream;


import com.google.common.base.Splitter;
import org.junit.Assert;
import org.junit.Test;

import java.util.StringTokenizer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SplitStreamPerfTest {

    private static final int TIMES = 1000;
    private static final String FIND = "10000";

    @Test
    public void go() throws Exception {
        final String longString = IntStream.rangeClosed(1,20000).boxed()
                .map(Object::toString)
                .collect(Collectors.joining(" ,"));

        IntStream.rangeClosed(1,3).forEach((i) -> {
            measureTime("Test " + i + " with regex", () -> doWithRegex(longString));
            measureTime("Test " + i + " with string tokenizer", () -> doWithStringTokenizer(longString));
            measureTime("Test " + i + " with guava", () -> doWithGuava(longString));
        });

    }

    private void measureTime(String name, Runnable r) {
        long s = System.currentTimeMillis();
        r.run();
        long elapsed = System.currentTimeMillis() - s;
        System.out.println("Check " + name +" took " + elapsed + " ms");
    }

    private void doWithStringTokenizer(String longString) {

        String f = null;
        for (int i = 0; i < TIMES; i++) {
            StringTokenizer st = new StringTokenizer(longString,",",false);
            while (st.hasMoreTokens()) {
                String t = st.nextToken().trim();
                if (FIND.equals(t)) {
                    f = t;
                    break;
                }
            }
        }
        Assert.assertEquals(FIND, f);
    }


    private void doWithRegex(String longString) {
        final Pattern pattern = Pattern.compile(",");
        String f = null;
        for (int i = 0; i < TIMES; i++) {
            f = pattern.splitAsStream(longString)
                    .map(String::trim)
                    .filter(FIND::equals)
                    .findFirst().orElse("");
        }
        Assert.assertEquals(FIND, f);
    }


    private void doWithGuava(String longString) {
        final Splitter splitter = Splitter.on(',').trimResults();
        String f = null;
        for (int i = 0; i < TIMES; i++) {
            Iterable<String> iterable = splitter.split(longString);
            for (String s : iterable) {
                if (FIND.equals(s)) {
                    f = s;
                    break;
                }
            }
        }
        Assert.assertEquals(FIND, f);
    }
}

结果是(热身后)

Check Test 3 with regex took 1359 ms
Check Test 3 with string tokenizer took 750 ms
Check Test 3 with guava took 594 ms

如何使Java实现与Guava一样快?也许我做错了?

或者你可能知道任何工具/库和Guava Splitter一样快,它不涉及为这一个提取大量未使用的类吗?

4 个答案:

答案 0 :(得分:1)

首先,番石榴比<{1}},SplitterPredicate 更多 - 您可能没有使用它提供的所有东西;我们使用它硬核,只是听到让我颤抖。无论如何,你的测试都被破坏了 - 可能有很多种方式。我已经使用Function来测试这两种方法,只是为了它的乐趣:

JMH

结果:

    @BenchmarkMode(org.openjdk.jmh.annotations.Mode.AverageTime) 
    @OutputTimeUnit(TimeUnit.NANOSECONDS) 
    @Warmup(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)   
    @Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS) 
    @State(Scope.Thread) public class GuavaTest {

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(GuavaTest.class.getSimpleName())
                .jvmArgs("-ea", "-Xms10g", "-Xmx10g")
                .shouldFailOnError(true)
                .build();
        new Runner(opt).run();
    }

    @Param(value = { "300", "1000" })
    public String tokenToSearchFor;

    @State(Scope.Benchmark)
    public static class ThreadState {
        String longString = IntStream.range(1, 20000).boxed().map(Object::toString).collect(Collectors.joining(" ,"));

        StringTokenizer st = null;

        Pattern pattern = null;

        Splitter splitter = null;

        @Setup(Level.Invocation)
        public void setUp() {
            st = new StringTokenizer(longString, ",", false);
            pattern = Pattern.compile(",");
            splitter = Splitter.on(',').trimResults();
        }
    }

    @Benchmark
    @Fork(1)
    public boolean doWithStringTokenizer(ThreadState ts) {
        while (ts.st.hasMoreTokens()) {
            String t = ts.st.nextToken().trim();
            if (t.equals(tokenToSearchFor)) {
                return true;
            }
        }
        return false;
    }

    @Benchmark
    @Fork(1)
    public boolean doWithRegex(ThreadState ts) {
        return ts.pattern.splitAsStream(ts.longString)
                .map(String::trim)
                .anyMatch(tokenToSearchFor::equals);
    }

    @Benchmark
    @Fork(1)
    public boolean doWithGuava(ThreadState ts) {
        Iterable<String> iterable = ts.splitter.split(ts.longString);
        for (String s : iterable) {
            if (s.equals(tokenToSearchFor)) {
                return true;
            }
        }
        return false;
    }

}

这使番石榴成为最快的。

如果您将Benchmark (tokenToSearchFor) Mode Cnt Score Error Units GuavaTest.doWithGuava 300 avgt 5 19284.192 ± 23536.321 ns/op GuavaTest.doWithGuava 1000 avgt 5 67182.531 ± 93242.266 ns/op GuavaTest.doWithRegex 300 avgt 5 65780.954 ± 169044.641 ns/op GuavaTest.doWithRegex 1000 avgt 5 182530.069 ± 409571.222 ns/op GuavaTest.doWithStringTokenizer 300 avgt 5 34111.030 ± 61014.332 ns/op GuavaTest.doWithStringTokenizer 1000 avgt 5 118963.048 ± 165510.183 ns/op 添加到parallel,那么它就会变得有趣,必须阅读here

答案 1 :(得分:0)

这可能很有用,您可以只导入guava中需要的部分: https://github.com/google/guava/wiki/UsingProGuardWithGuava

答案 2 :(得分:0)

你能给出pattern.split(text)并在正常的for循环中迭代结果,试试看。它可能比流更快。 虽然我不确定它是否能击败番石榴。

我的意思是......

private void doWithRegexAndSplit(String longString) {
        final Pattern pattern = Pattern.compile(",");
        for (int i = 0; i < TIMES; i++) {
         String f = "";
         String[] arr = pattern.split(longString);
            for (int i = 0; i < arr.length; i++){
                String t= arr[i].trim();
                if (FIND.equals(t)) {
                f = t;
                break;
                }
            }       
        }
        Assert.assertEquals(FIND, f);
    }

请检查此案件的完成时间。

答案 3 :(得分:0)

您正在Pattern.splitAsStream(CharSequence)而不是Splitter.split(CharSequence)上将Splitter.on(char)Splitter.onPattern(String)进行比较。查找与char的匹配在计算上要比查找模式匹配(正则表达式)简单得多。

如果您使用WorkflowID,您将获得如下结果:

Splitter.onPattern(",").trimResults()

在哪种情况下Check Test 3 with regex took 608 ms Check Test 3 with string tokenizer took 403 ms Check Test 3 with guava took 306 ms Check Test 3 with guava pattern took 689 ms 实际上比Guava的实施表现更好(假设这是一个有效的基准,这总是有问题,因为我们不使用jmh)。

我不知道任何JDK Pattern.splitAsStrimg(CharSequence)分隔解决方案类似于Guava的char。您可以自己动手,但Guava的解决方案似乎非常优化。