应用风格的计算成本 [英] Computational cost of applicative style
问题描述
我在我的网络应用程序中使用了一个小型数据库池。这个特殊的函数:
pre $ withPool pool =括号(takeConn池)(putConn池)
可以用适用风格重写:
withPool =括号< $> takeConn * putConn
可以说它的可读性更高,更加优雅。所以很自然,我想写这样写。但是数据库连接池应该很快,而且我担心这种风格会带来不必要的开销。
所以我的问题是,多少开销(如果有)使用Haskell中会出现应用函子吗?是否有任何基准?
我真的怀疑他们在大多数情况下会被编译为相同的东西。
我做了一个小测试,
import Control.Applicative
test1 ::( b→b→c)→> (a - > b) - > (a - > b) - > a - > c
test1括号takeConn putConn池=括号(takeConn池)(putConn池)
test2 ::(b - > b - > c) - > (a - > b) - > (a - > b) - > a - > c
test2括号takeConn putConn =括号< $> takeConn * putConn
但我将test2的类型限制为只有函数(这不是它最通用的然后我用 ghc -O -ddump-simpl
编译得到某种排序从GHC的中间输出(我尝试了C输出,它太丑了),而且两个看起来完全一样,除了名称。
(我也尝试过没有-O虽然,他们是不一样的,如果我离开类型注释)
I am using a small database pool in my web app. And this particular function:
withPool pool = bracket (takeConn pool) (putConn pool)
can be rewritten in applicative style:
withPool = bracket <$> takeConn <*> putConn
Arguably it is just as readable and much more elegant. So naturally, I want to write it like that. But database connection pool supposed to be fast, and I am afraid that this style introduces unnecessary overhead.
So my question is, how much overhead (if any) does use of applicative functors incur in Haskell? Are there any benchmarks?
I really suspect they'll be compiled down to the same thing in most cases. I did a tiny test,
import Control.Applicative
test1 :: (b -> b -> c) -> (a -> b) -> (a -> b) -> a -> c
test1 bracket takeConn putConn pool = bracket (takeConn pool) (putConn pool)
test2 :: (b -> b -> c) -> (a -> b) -> (a -> b) -> a -> c
test2 bracket takeConn putConn = bracket <$> takeConn <*> putConn
but I am constraining the type of test2 there to only functions (which isn't its most generalised type, right..?)
Then I compiled with ghc -O -ddump-simpl
to get some sort of intermediate output from GHC (I tried the C output, it was too ugly) and the two came out looking exactly the same, except for names.
(I also tried without -O though, and they weren't the same, nor if I leave out the type annotations)
这篇关于应用风格的计算成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!