Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

Improved performance from strict Comma constructor

Three variants of mappend were benchmarked,  along with both lazy and strict
Comma constructors,  for a total of 6 variations.  Of the three combinations
that lead to a "lazy" mappend,  variant 2 with a lazy comma performed worst,
but I did not discern a performance difference between variant 2 with a
strict comma and variant 3 with a lazy comma.   The strict combinations
performed somewhat better in this benchmark, but I feel that the lazier
semantics is important,  so I went with variant 2 with a strict comma.

--- Variant 1
--- This is always strict

  mappend Empty x = x
  mappend x Empty = x
  mappend (Comma a) (Comma b)
        = Comma (a ++ fromChar ',' ++ b)

--- Variant 2
--- This is always Lazy,  but Comma should be strict for better performance
  mappend Empty     x = x
  mappend (Comma a) x
        = Comma (a ++ case x of
                        Empty   -> mempty
                        Comma b -> fromChar ',' ++ b)

--- Variant 3
--- This is strict if and only if Comma is strict
  mappend Empty x = x
  mappend (Comma a) x
        = Comma (case x of
                   Empty   -> a
                   Comma b -> a ++ fromChar ',' ++ b)

However,  Variant 3 with a lazy comma can be differentiated from Variant 2 by
following expression:

toJsonLazyByteString (         mconcat (map element [1..big_number])
                     `mappend` mconcat (repeat mempty))

where big_number is big enough to fill up a chunk of the lazy bytestring.
Variant 2 will produce chunks before entering the non-productive infinite loop,
whereas Variant 3 will never produce anything.
  • Loading branch information...
commit b33adc7c8a959cec918485900cc3c8360b23854d 1 parent f9873e1
@lpsmith authored
Showing with 1 addition and 1 deletion.
  1. +1 −1  src/Data/Json/Builder/Internal.hs
2  src/Data/Json/Builder/Internal.hs
@@ -102,7 +102,7 @@ instance Value Array where
data CommaMonoid
= Empty
- | Comma Builder
+ | Comma !Builder
instance Monoid CommaMonoid where
mempty = Empty

0 comments on commit b33adc7

Please sign in to comment.
Something went wrong with that request. Please try again.