From 0df8ce27f1c418fee1ba860f1c6575f66cae2ca7 Mon Sep 17 00:00:00 2001
From: Vladislav Zavialov <vlad.z.4096@gmail.com>
Date: Sat, 3 Feb 2024 02:15:53 +0300
Subject: [PATCH] Reduce parser allocations in allocateCommentsP

In the most common case, the comment queue is empty, so we can skip the
work of processing it. This reduces allocations by about 10% in the
parsing001 test.

Metric Decrease:
    MultiLayerModulesRecomp
    parsing001
---
 compiler/GHC/Parser/Lexer.x        | 1 +
 compiler/GHC/Parser/PostProcess.hs | 1 +
 2 files changed, 2 insertions(+)

diff --git a/compiler/GHC/Parser/Lexer.x b/compiler/GHC/Parser/Lexer.x
index 50354242acf8..cff79b44136f 100644
--- a/compiler/GHC/Parser/Lexer.x
+++ b/compiler/GHC/Parser/Lexer.x
@@ -3235,6 +3235,7 @@ instance MonadP P where
   getBit ext = P $ \s -> let b =  ext `xtest` pExtsBitmap (options s)
                          in b `seq` POk s b
   allocateCommentsP ss = P $ \s ->
+    if null (comment_q s) then POk s emptyComments else  -- fast path
     let (comment_q', newAnns) = allocateComments ss (comment_q s) in
       POk s {
          comment_q = comment_q'
diff --git a/compiler/GHC/Parser/PostProcess.hs b/compiler/GHC/Parser/PostProcess.hs
index 1dcab296d2ef..75ebca80f8c5 100644
--- a/compiler/GHC/Parser/PostProcess.hs
+++ b/compiler/GHC/Parser/PostProcess.hs
@@ -3060,6 +3060,7 @@ instance MonadP PV where
       let b = ext `xtest` pExtsBitmap (pv_options ctx) in
       PV_Ok acc $! b
   allocateCommentsP ss = PV $ \_ s ->
+    if null (pv_comment_q s) then PV_Ok s emptyComments else  -- fast path
     let (comment_q', newAnns) = allocateComments ss (pv_comment_q s) in
       PV_Ok s {
          pv_comment_q = comment_q'
-- 
GitLab