From 814f76443ecda9c5129be9ce8b89bd6554891ecc Mon Sep 17 00:00:00 2001
From: Hans-Peter Deifel <hpd@hpdeifel.de>
Date: Mon, 8 Oct 2018 23:12:14 +0200
Subject: [PATCH] Speed up MorphismEncoding creation from parser state

By not looking up every State individually in the HashMap of H1s, we
can gain a little more performance.
---
 src/MA/Coalgebra/Parser.hs | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/src/MA/Coalgebra/Parser.hs b/src/MA/Coalgebra/Parser.hs
index b190bbc..b2faf2c 100644
--- a/src/MA/Coalgebra/Parser.hs
+++ b/src/MA/Coalgebra/Parser.hs
@@ -13,7 +13,7 @@ module MA.Coalgebra.Parser
   , module MA.Coalgebra.Parser.Class
   ) where
 
-import           Control.Monad (void)
+import           Control.Monad (void, forM_)
 import           Data.Bifunctor
 import           Data.Tuple
 import           Data.Void (Void)
@@ -25,6 +25,7 @@ import qualified Data.Text as T
 import           Lens.Micro.Platform
 import           Text.Megaparsec hiding (State)
 import qualified Data.Vector as V
+import qualified Data.Vector.Mutable as VM
 import           Control.DeepSeq (NFData)
 
 import           Data.MorphismEncoding (Encoding, State)
@@ -80,10 +81,10 @@ finalizeState :: forall f.
 finalizeState state =
   let
     h1s = state ^. h1Map
-    h1Vec = V.generate (M.size h1s) $ \i ->
-      case M.lookup i h1s of
-        Nothing -> error "should not happen" -- FIXME: Handle this case better
-        Just x -> x
+    h1Vec = V.create $ do
+      v <- VM.unsafeNew (M.size h1s)
+      forM_ (M.toList h1s) $ \(i, h1) -> VM.unsafeWrite v i h1
+      return v
     !edges = V.concat (state ^. graph)
     !symTab = M.fromList (map swap (M.toList (fmap fst (state ^. symbolTable))))
 
-- 
GitLab