繁体   English   中英

Clojure:输入流比读取器慢

[英]Clojure: input-stream slower than reader

我正在尝试从输入流中读取字节,它比使用读取器读取字符慢得多。 我不知道为什么会这样。 看一下测试:

(defn r1
  [input]
  (loop []
    (when-not (= -1 (.read ^java.io.InputStream input))
      (recur))))

(defn r2
  [input]
  (loop []
    (when-not (.read input)
      (recur))))

(dotimes [_ 10] 
   (time (with-open [is (clojure.java.io/input-stream "15mb.log")]
     (r1 is))))

"Elapsed time: 111.608991 msecs"
"Elapsed time: 95.45663 msecs"
"Elapsed time: 148.789867 msecs"
"Elapsed time: 97.580527 msecs"
"Elapsed time: 113.093759 msecs"
"Elapsed time: 108.306019 msecs"
"Elapsed time: 107.71069 msecs"
"Elapsed time: 104.833343 msecs"
"Elapsed time: 174.701027 msecs"
"Elapsed time: 141.969629 msecs"

(dotimes [_ 10]
   (time (with-open [r (clojure.java.io/reader "15mb.log")]
      (r2 r))))

"Elapsed time: 0.635769 msecs"
"Elapsed time: 0.422315 msecs"
"Elapsed time: 0.355953 msecs"
"Elapsed time: 0.336128 msecs"
"Elapsed time: 0.333523 msecs"
"Elapsed time: 0.339613 msecs"
"Elapsed time: 0.329693 msecs"
"Elapsed time: 0.234213 msecs"
"Elapsed time: 0.209742 msecs"
"Elapsed time: 0.199334 msecs"

据我所知,clojure.java.io/input-stream使用BufferedInputStream,而clojure.java.io/reader使用BufferedReader,因此没有理由在速度上有如此大的差异。 我想念什么吗?

您的测试有缺陷。 BufferedReaderBufferedInputStream在流的末尾都返回-1 因此,您对r2的测试也应该是(when-not (= -1 (.read ...

尽管下面的测试方法无法精确到毫秒级,但对于该测试来说还是足够准确的,并且使用非常好的criterium基准库对clojure进行的测试会产生相似的结果。 再次紧凑地发布测试,以便于复制/粘贴:

(let [testfile "zerofile"]    ; $ dd if=/dev/zero of=zerofile bs=1k count=1k
  (map (fn [func label]
         (println label)
         (dotimes [_ 3]
           (time (with-open [data (func testfile)]
                   (while (not= -1 (.read data)))))))
    [clojure.java.io/input-stream,  clojure.java.io/reader]
    ["Input Stream:" "\nReader:"]))

一个结果:

Input Stream:
"Elapsed time: 624.01494 msecs"
"Elapsed time: 650.407183 msecs"
"Elapsed time: 627.244097 msecs"

Reader:
"Elapsed time: 706.776733 msecs"
"Elapsed time: 691.887275 msecs"
"Elapsed time: 703.918226 msecs"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM