Skip to content

Commit 7e444a1

Browse files
committed
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.
1 parent aa79c92 commit 7e444a1

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

Control/Concurrent/STM/TArray.hs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,18 @@ import Control.Sequential.STM (STM)
4141
-- but it may be replaced by a more efficient implementation in the future
4242
-- (the interface will remain the same, however).
4343
--
44-
newtype TArray i e = TArray (Array i (TVar e)) deriving (Eq, Typeable)
44+
newtype TArray i e = TArray (Array i (TVar e)) deriving (Typeable)
45+
46+
-- There are no provisions for moving/copying TVars between TArrays.
47+
-- Therefore, two TArrays are equal if and only if they are both empty or are
48+
-- actually the same array in memory. We have no safe operations for checking
49+
-- that directly (though in practice we could use `unsafeCoerce#` with
50+
-- `sameMutableArray#`). So instead we take a quick look at the array sizes and
51+
-- then decide based on the first TVar of each.
52+
instance Eq (TArray i e) where
53+
TArray t1 == TArray t2
54+
= numElements t1 == numElements t2
55+
&& (numElements t1 == 0 || unsafeAt t1 0 == unsafeAt t2 0)
4556

4657
instance MArray TArray e STM where
4758
getBounds (TArray a) = return (bounds a)

0 commit comments

Comments
 (0)