Skip to content

Commit 6221be7

Browse files
Speed up keys by using foldrWithIndex (#62)
* Speed up `keys` by using foldrWithIndex
1 parent ba5f689 commit 6221be7

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Breaking changes:
1010
New features:
1111
- Exported `Data.Map.Internal` data constructors (#52 by @natefaubion)
1212
- Add unbiased `Semigroup`/`Monoid` instances to `Map` with `Warn` (#54 by @JordanMartinez)
13-
- Improved speed of `foldr`, `foldl`, `foldMap`, `foldlWithIndex`, `foldrWithIndex`, `foldMapWithIndex`, `unionWith`, and `values` (#60 by @xgrommx, #61 by @JordanMartinez)
13+
- Improved speed of `foldr`, `foldl`, `foldMap`, `foldlWithIndex`, `foldrWithIndex`, `foldMapWithIndex`, `unionWith`, `keys` and `values` (#60 by @xgrommx, #61 and #62 by @JordanMartinez)
1414

1515
Bugfixes:
1616

bench/Bench/Data/Map.purs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ benchMap = do
4242
log "---------------"
4343
benchValues
4444

45+
log ""
46+
47+
log "keys"
48+
log "---------------"
49+
benchKeys
50+
4551
where
4652

4753
benchUnion = do
@@ -76,6 +82,20 @@ benchMap = do
7682
log $ "M.values: big map (" <> show size' <> ")"
7783
benchWith 10 \_ -> M.values bigMap'
7884

85+
benchKeys = do
86+
let nats = L.range 0 999999
87+
natPairs = (flip Tuple) unit <$> nats
88+
bigMap = Map2a0bff.fromFoldable $ natPairs
89+
bigMap' = M.fromFoldable $ natPairs
90+
size = Map2a0bff.size bigMap
91+
size' = M.size bigMap'
92+
93+
log $ "Map2a0bff.keys: big map (" <> show size <> ")"
94+
benchWith 10 \_ -> Map2a0bff.keys bigMap
95+
96+
log $ "M.keys: big map (" <> show size' <> ")"
97+
benchWith 10 \_ -> M.keys bigMap'
98+
7999
benchSize = do
80100
let nats = L.range 0 999999
81101
natPairs = (flip Tuple) unit <$> nats

src/Data/Map/Internal.purs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -651,9 +651,7 @@ toUnfoldableUnordered m = unfoldr go (m : Nil) where
651651

652652
-- | Get a list of the keys contained in a map
653653
keys :: forall k v. Map k v -> List k
654-
keys Leaf = Nil
655-
keys (Two left k _ right) = keys left <> pure k <> keys right
656-
keys (Three left k1 _ mid k2 _ right) = keys left <> pure k1 <> keys mid <> pure k2 <> keys right
654+
keys = foldrWithIndex (\k _ acc -> k : acc) Nil
657655

658656
-- | Get a list of the values contained in a map
659657
values :: forall k v. Map k v -> List v

0 commit comments

Comments
 (0)