From 1cca8ccca020d458dd516ae87ab6913e30a19324 Mon Sep 17 00:00:00 2001 From: Jordan Gillard Date: Tue, 9 May 2023 14:33:35 -0400 Subject: [PATCH] Improve and refactor cellseqs_v2 in Nim standard library (#21796) * Refactor and optimize cellseqs_v2 in Nim standard library * Extract resizing logic into a separate 'resize' procedure for better readability and separation of concerns * Implement realloc for non-threaded cases to improve memory operations efficiency * Use ',' instead of ';' between parameters in 'add' procedure for consistency with other Nim code * Respond to Araq's feedback: Refactor resize function to use reallocShared This commit replaces the usage of allocShared and deallocShared with reallocShared to optimize memory allocation and deallocation while resizing the CellSeq. (cherry picked from commit b169dad1e5083eae333ba9a7e11fed74a05385de) --- lib/system/cellseqs_v2.nim | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/lib/system/cellseqs_v2.nim b/lib/system/cellseqs_v2.nim index 27be48d78e..c6c7b1a8e2 100644 --- a/lib/system/cellseqs_v2.nim +++ b/lib/system/cellseqs_v2.nim @@ -16,20 +16,17 @@ type len, cap: int d: CellArray[T] -proc add[T](s: var CellSeq[T], c: T; t: PNimTypeV2) {.inline.} = +proc resize[T](s: var CellSeq[T]) = + s.cap = s.cap * 3 div 2 + var newSize = s.cap * sizeof(CellTuple[T]) + when compileOption("threads"): + s.d = cast[CellArray[T]](reallocShared(s.d, newSize)) + else: + s.d = cast[CellArray[T]](realloc(s.d, newSize)) + +proc add[T](s: var CellSeq[T], c: T, t: PNimTypeV2) {.inline.} = if s.len >= s.cap: - s.cap = s.cap * 3 div 2 - when compileOption("threads"): - var d = cast[CellArray[T]](allocShared(uint(s.cap * sizeof(CellTuple[T])))) - else: - var d = cast[CellArray[T]](alloc(s.cap * sizeof(CellTuple[T]))) - copyMem(d, s.d, s.len * sizeof(CellTuple[T])) - when compileOption("threads"): - deallocShared(s.d) - else: - dealloc(s.d) - s.d = d - # XXX: realloc? + s.resize() s.d[s.len] = (c, t) inc(s.len)