你好,Stackoverflow社区。
我相对来说是Haskell的新手,并且我注意到使用writeFile
或hPutStr
将大字符串写入文件非常缓慢。
对于一个1.5MB的字符串,我的程序(使用ghc编译)需要大约2秒钟,而“相同”的C++代码只需要大约0.1秒钟。该字符串是从大约10000个元素的列表生成的,然后使用writeFile
进行转储。我还尝试了使用mapM_
和hPutStr
遍历列表,结果相同。
有更快的方法来写入大字符串吗?
更新
正如@applicative指出的,以下代码在很短的时间内完成了一个大小为2MB的文件。
main = readFile "input.txt" >>= writeFile "ouput.txt"
我的问题似乎出在其他地方。以下是我两个实现写列表的代码(WordIndex和CoordList是Map和List的类型别名)
使用hPutStrLn
-- Print to File
indexToFile :: String -> WordIndex -> IO ()
indexToFile filename index =
let
indexList = map (\(k, v) -> entryToString k v) (Map.toList index)
in do
output <- openFile filename WriteMode
mapM_ (\v -> hPutStrLn output v) indexList
hClose output
-- Convert Listelement to String
entryToString :: String -> CoordList -> String
entryToString key value = (embedString 25 key) ++ (coordListToString value) ++ "\n"
with writeFile
-- Print to File
indexToFile :: String -> WordIndex -> IO ()
indexToFile filename index = writeFile filename (indexToString "" index)
-- Index to String
indexToString :: String -> WordIndex -> String
indexToString lead index = Map.foldrWithKey (\k v r -> lead ++ (entryToString k v) ++ r) "" index
也许你们可以帮我加快速度。
提前感谢。
main = readFile "1.5mb.txt" >>= writeFile "1.5mb2.txt"
只需要0m0.089s
,而不是你所报告的 C++ 的 2 秒,因此更快。当文件大小约为 50 MB 时,它开始接近 2 秒;同样,writeFile "big.txt" (show [1..250000])
只需 0.06 秒,并生成一个 1.6 mb 的文件。 - applicative