Skip to content

Commit d587677

Browse files
committed
feat: faster ChunkEntries
1 parent 28a4d94 commit d587677

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

map.go

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -254,34 +254,24 @@ func ChunkEntries[K comparable, V any](m map[K]V, size int) []map[K]V {
254254
panic("The chunk size must be greater than 0")
255255
}
256256

257-
keys := make([]K, 0, len(m))
258-
for key := range m {
259-
keys = append(keys, key)
260-
}
261-
262-
if len(keys) == 0 {
257+
count := len(m)
258+
if count == 0 {
263259
return []map[K]V{}
264260
}
265261

266-
chunksNum := len(keys) / size
267-
if len(keys)%size != 0 {
262+
chunksNum := count / size
263+
if count%size != 0 {
268264
chunksNum += 1
269265
}
270266

271267
result := make([]map[K]V, 0, chunksNum)
272268

273-
for i := 0; i < chunksNum; i++ {
274-
start := i * size
275-
end := (i + 1) * size
276-
if end > len(keys) {
277-
end = len(keys)
269+
for k, v := range m {
270+
if len(result) == 0 || len(result[len(result)-1]) == size {
271+
result = append(result, make(map[K]V, size))
278272
}
279273

280-
chunk := make(map[K]V)
281-
for _, key := range keys[start:end] {
282-
chunk[key] = m[key]
283-
}
284-
result = append(result, chunk)
274+
result[len(result)-1][k] = v
285275
}
286276

287277
return result

0 commit comments

Comments
 (0)