Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Nim Memory Management

БесплатноБез исполняемых скриптовНе проверен

Use when nim's memory management including garbage collection strategies, manual memory control, destructors, move semantics, ref/ptr types, memory safety…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Nim Memory Management

Introduction

Nim provides flexible memory management combining automatic garbage collection with manual control options. This hybrid approach enables safe high-level programming while allowing low-level optimization for performance-critical code. Understanding memory management is crucial for systems programming and embedded applications.

Nim supports multiple garbage collectors (GC), move semantics for efficiency, destructors for resource cleanup, and manual memory management through pointers. The compiler's static analysis prevents many memory errors at compile time, while runtime checks catch others during development.

This skill covers garbage collection strategies, ref vs ptr types, move semantics, destructors and hooks, manual memory management, memory safety patterns, and optimization techniques for minimal allocations and predictable performance.

Garbage Collection Strategies

Nim offers multiple GC implementations with different trade-offs for throughput, latency, and memory usage.

# Default GC (--gc:refc)
# Reference counting with cycle detection
type Node = ref object
  value: int
  next: Node

var head = Node(value: 1)
head.next = Node(value: 2)
head.next.next = Node(value: 3)

# Arc GC (--gc:arc)
# Automatic reference counting without cycle detection
# Fastest but requires breaking cycles manually
{.experimental: "strictFuncs".}

proc processData() =
  var data = @[1, 2, 3, 4, 5]  # Heap allocated
  # Automatically freed when out of scope
  echo data

# ORC GC (--gc:orc)
# Arc with cycle collection
proc createCycle() =
  type
    Node = ref object
      next: Node

  var a = Node()
  var b = Node()
  a.next = b
  b.next = a  # Cycle collected by ORC

# Manual GC control
proc lowLatencyOperation() =
  GC_disable()  # Disable GC during critical section
  # Time-sensitive code here
  GC_enable()

# GC statistics
proc checkMemory() =
  echo "GC Memory: ", getOccupiedMem()
  echo "GC Total: ", getTotalMem()
  echo "GC Free: ", getFreeMem()

# Forcing collection
proc cleanupMemory() =
  GC_fullCollect()  # Force full collection

# GC hints
proc allocateLarge() =
  var data: ref array[1000000, int]
  new(data)
  GC_ref(data)  # Add external reference
  # Use data
  GC_unref(data)  # Remove reference

# Region-based allocation
proc useRegion() =
  var region: MemRegion
  region = newMemRegion()
  # Allocations in region
  freeMemRegion(region)

# Stack allocation for value types
proc stackAlloc() =
  var data: array[1000, int]  # Stack allocated
  # Automatically freed on scope exit

# Compile-time GC selection
when defined(gcArc):
  echo "Using Arc GC"
elif defined(gcOrc):
  echo "Using ORC GC"
else:
  echo "Using default GC"

# GC-safe operations
{.push gcsafe.}
proc threadSafeProc() =
  echo "No global GC state accessed"
{.pop.}

Choose GC strategy based on application needs: Arc for speed, ORC for safety, refc for compatibility.

Ref and Ptr Types

Ref types use garbage collection while ptr types require manual memory management.

# Ref types (GC-managed)
type
  Person = ref object
    name: string
    age: int

proc createPerson(): Person =
  Person(name: "Alice", age: 30)

var p = createPerson()
# Automatically freed by GC

# Ptr types (manual management)
type
  Buffer = ptr object
    data: array[1024, byte]
    size: int

proc createBuffer(): Buffer =
  cast[Buffer](alloc0(sizeof(Buffer)))

proc destroyBuffer(buf: Buffer) =
  dealloc(buf)

# Using ptr types
proc useBuffer() =
  var buf = createBuffer()
  # Use buffer
  destroyBuffer(buf)

# Ref vs ptr performance
proc refExample() =
  var items: seq[ref int]
  for i in 0..<1000:
    var x: ref int
    new(x)
    x[] = i
    items.add(x)

proc ptrExample() =
  var items: seq[ptr int]
  for i in 0..<1000:
    var x = cast[ptr int](alloc(sizeof(int)))
    x[] = i
    items.add(x)

  # Manual cleanup required
  for item in items:
    dealloc(item)

# Shared pointers
type SharedPtr[T] = ref object
  data: T
  refCount: int

proc newShared[T](value: T): SharedPtr[T] =
  SharedPtr[T](data: value, refCount: 1)

# Weak references
type
  WeakRef[T] = object
    target: ptr T

proc newWeakRef[T](target: ref T): WeakRef[T] =
  WeakRef[T](target: cast[ptr T](target))

# Pointer arithmetic
proc ptrArithmetic() =
  var arr = [1, 2, 3, 4, 5]
  var p = addr arr[0]
  p = cast[ptr int](cast[int](p) + sizeof(int))
  echo p[]  # 2

# Safe pointer usage
proc safePtrUsage() =
  var x = 42
  var p = addr x  # Stack address
  echo p[]  # Safe while x in scope
  # p becomes invalid after scope

# Pointer aliasing
proc aliasing() =
  var x = 10
  var p1 = addr x
  var p2 = addr x
  p1[] = 20
  echo p2[]  # 20

Use ref for automatic memory management, ptr for manual control and C interop.

Move Semantics and Ownership

Move semantics transfer ownership without copying, improving performance for large data structures.

# Move vs copy
proc moveExample() =
  var s1 = @[1, 2, 3, 4, 5]
  var s2 = s1  # Copy
Полный SKILL.md на GitHub

Установить Nim Memory Management в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Nim Memory Management?

Use when nim's memory management including garbage collection strategies, manual memory control, destructors, move semantics, ref/ptr types, memory safety, and optimization techniques for performance-critical systems programming.

Как установить скилл Nim Memory Management?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Nim Memory Management запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Nim Memory Management с