Skip to content

Commit

Permalink
Optimize storing into uninit locations for arrays and seqs. (nim-lang…
Browse files Browse the repository at this point in the history
  • Loading branch information
planetis-m authored Jan 19, 2025
1 parent 2af9ddc commit 6481482
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
12 changes: 7 additions & 5 deletions lib/system.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2965,14 +2965,16 @@ when notJSnotNims and not defined(nimSeqsV2):
assert y == "abcgh"
discard

proc arrayWith*[T](y: T, size: static int): array[size, T] {.raises: [].} =
proc arrayWith*[T](y: T, size: static int): array[size, T] {.noinit, nodestroy, raises: [].} =
## Creates a new array filled with `y`.
result = zeroDefault(array[size, T])
for i in 0..size-1:
result[i] = y
when (NimMajor, NimMinor, NimPatch) >= (2, 3, 1):
result[i] = `=dup`(y)
else:
wasMoved(result[i])
`=copy`(result[i], y)

proc arrayWithDefault*[T](size: static int): array[size, T] {.raises: [].} =
proc arrayWithDefault*[T](size: static int): array[size, T] {.noinit, nodestroy, raises: [].} =
## Creates a new array filled with `default(T)`.
result = zeroDefault(array[size, T])
for i in 0..size-1:
result[i] = default(T)
7 changes: 5 additions & 2 deletions lib/system/seqs_v2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,11 @@ proc grow*[T](x: var seq[T]; newLen: Natural; value: T) {.nodestroy.} =
xu.p = cast[typeof(xu.p)](prepareSeqAddUninit(oldLen, xu.p, newLen - oldLen, sizeof(T), alignof(T)))
xu.len = newLen
for i in oldLen .. newLen-1:
wasMoved(xu.p.data[i])
`=copy`(xu.p.data[i], value)
when (NimMajor, NimMinor, NimPatch) >= (2, 3, 1):
xu.p.data[i] = `=dup`(value)
else:
wasMoved(xu.p.data[i])
`=copy`(xu.p.data[i], value)

proc add*[T](x: var seq[T]; y: sink T) {.magic: "AppendSeqElem", noSideEffect, nodestroy.} =
## Generic proc for adding a data item `y` to a container `x`.
Expand Down

0 comments on commit 6481482

Please sign in to comment.