GHC Haskell performance of IPv4 address rendering

2019-05-16 00:06发布

问题:

I recently built a library for handling IPv4 address in haskell. I have written two functions to render an IPv4 address to Text and I am surprised that the naive approach outperforms the approach that I actually thought about. Here are the relevant pieces. First, there is the definition of IPv4:

newtype IPv4 = IPv4 { getIPv4 :: Word32 }

Next we have the IP address renderer that I expected to perform well:

toDotDecimalText :: IPv4 -> Text
toDotDecimalText = LText.toStrict . TBuilder.toLazyText . toDotDecimalBuilder
{-# INLINE toDotDecimalText #-}

toDotDecimalBuilder :: IPv4 -> TBuilder.Builder
toDotDecimalBuilder (IPv4 w) = 
  decimal (255 .&. shiftR w 24 )
  <> dot
  <> decimal (255 .&. shiftR w 16 )
  <> dot
  <> decimal (255 .&. shiftR w 8 )
  <> dot
  <> decimal (255 .&. w)
  where dot = TBuilder.singleton '.'
{-# INLINE toDotDecimalBuilder #-}

Finally, we have the naive implementation:

ipv4ToTextNaive :: IPv4 -> Text
ipv4ToTextNaive i = Text.pack $ concat
  [ show a
  , "."
  , show b
  , "."
  , show c
  , "."
  , show d
  ]
  where (a,b,c,d) = IPv4.toOctets i

And finally, here is the benchmark suite:

main :: IO ()
main = do
  let ipAddr = IPv4 1000000009
  defaultMain 
    [ bgroup "IPv4 to Text" 
      [ bench "Naive" $ whnf ipv4ToTextNaive ipAddr
      , bench "Current Implementation" $ whnf IPv4_Text.encode ipAddr
      ]
    ]

You can try this out by cloning the repository I've linked to and then running stack bench --benchmark-arguments '--output=out.html' in the top level directory of the project. The results I get are:

benchmarking IPv4 to Text/Naive
time                 391.1 ns   (389.9 ns .. 392.7 ns)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 394.2 ns   (393.1 ns .. 396.4 ns)
std dev              4.989 ns   (2.990 ns .. 7.700 ns)
variance introduced by outliers: 12% (moderately inflated)

benchmarking IPv4 to Text/Current Implementation
time                 467.5 ns   (466.0 ns .. 469.8 ns)
                     1.000 R²   (0.999 R² .. 1.000 R²)
mean                 470.9 ns   (467.8 ns .. 478.3 ns)
std dev              14.75 ns   (8.245 ns .. 26.96 ns)
variance introduced by outliers: 45% (moderately inflated)

The naive one (which uses [Char] and then packs it into Text at the end) beats the one I thought would do better (which uses a text Builder) every time.

I've consider several possibilities. One is that I've misused criterion or misunderstood weak head normal form for Text. Another is that a Builder doesn't perform like I thought it does. I always envisioned them as being like a difference list that was smarter about bitpacking, but from the definition, I'm really not all that sure what I should expect.