Codec.Binary.Base64.encode速度很慢

d8d*_*f42 5 haskell

我正在使用http://hackage.haskell.org/package/dataenc-0.14.0.5/docs/Codec-Binary-Base64.html#v:encode,我发现这非常慢:

import qualified Codec.Binary.Base64 as C
import System.Environment

main = do
    [arg] <- getArgs
    print $ length $ C.encode $ replicate (read arg) 80
Run Code Online (Sandbox Code Playgroud)

参数10 ^ 5的运行时间:0.5 s,2 * 10 ^ 5:3.4 s,3 * 10 ^ 5:9.4 s。但是这样的事情应该线性运行吗?

当我寻找问题的原因时-是否有解决方法(其他库)?

PS:这行代码https://github.com/magthe/dataenc/blob/master/src/Codec/Binary/Base64.hs#L77看起来非常有问题(即二次):

doEnc acc (o1:o2:o3:os) = doEnc (acc ++ enc3 [o1, o2, o3]) os
doEnc acc os = EPart acc (eI os)
Run Code Online (Sandbox Code Playgroud)

果然,使用简单的代码

encode ws = case ws of
    [] -> [] 
    o1:ws2 -> case ws2 of
        [] -> take 2 (enc3 [o1,0,0]) ++ "=="
        o2:ws3 -> case ws3 of
            [] -> take 3 (enc3 [o1,o2,0]) ++ "="
            o3:ws4 -> enc3 [o1,o2,o3] ++ encode ws4
Run Code Online (Sandbox Code Playgroud)

已经大大改善了(例如,以4 s编码的10 ^ 8字节)

PPS:根据以下建议,该程序

import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as B64
import System.Environment

main = do
    [arg] <- getArgs
    print $ B.length $ B64.encode $ B.replicate (read arg) 80
Run Code Online (Sandbox Code Playgroud)

在0.4秒内编码10 ^ 8个字节。

J. *_*son 3

尝试一下图书馆base64-bytestring。通常ByteString在处理二进制数据时使用 s 将极大地提高性能。列表类型由于其简单性而作为控制结构很有用,但性能不佳。