From 430db74fe069352f40a67aaa72b589566c086db3 Mon Sep 17 00:00:00 2001 From: David Feuer Date: Wed, 16 Sep 2020 12:23:21 -0400 Subject: [PATCH] Speed up the Eq instance for TArray We don't actually have to check all the elements to see that two `TArray`s are equal. --- Control/Concurrent/STM/TArray.hs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Control/Concurrent/STM/TArray.hs b/Control/Concurrent/STM/TArray.hs index 1d26c21..b849136 100644 --- a/Control/Concurrent/STM/TArray.hs +++ b/Control/Concurrent/STM/TArray.hs @@ -41,7 +41,18 @@ import Control.Sequential.STM (STM) -- but it may be replaced by a more efficient implementation in the future -- (the interface will remain the same, however). -- -newtype TArray i e = TArray (Array i (TVar e)) deriving (Eq, Typeable) +newtype TArray i e = TArray (Array i (TVar e)) deriving (Typeable) + +-- There are no provisions for moving/copying TVars between TArrays. +-- Therefore, two TArrays are equal if and only if they are actually +-- the same array in memory. We have no safe operations for checking that +-- directly (though in practice we could use `unsafeCoerce#` with +-- `sameMutableArray#`). So instead we take a quick look at the array +-- sizes and then decide based on the first TVar of each. +instance Eq (TArray i e) where + TArray t1 == TArray t2 + = numElements t1 == numElements t2 + && (numElements t1 == 0 || unsafeAt t1 0 == unsafeAt t2 0) instance MArray TArray e STM where getBounds (TArray a) = return (bounds a)