Technical Reference

Type Definitions

SweepTask

A SweepTask can be any of the following:

type SweepTask = (() -> ()) | Destructable | RBXScriptConnection | thread

SweepTasks are the fundamental unit of cleanup in the Sweep framework. They can be functions, objects, connections, or threads.

TypeDescription
FunctionA function that can be called for cleanup
DestructableInstance or object with Destroy method
RBXScriptConnectionRBXScriptConnection
threadCoroutine

Destructable

type Destructable = Instance | { Destroy: () -> () }

A Destructable can be either:

Internal Implementation Details

Task Storage

Tasks are stored internally in the Sweep instance using two main tables:

self._tasks = {} -- Stores the actual tasks
self._labels = {} -- Stores optional debug labels for tasks

Task Indexing

Tasks use a numerical indexing system:

  • Tasks are indexed numerically starting from 1
  • Each task gets a unique ID returned by GiveTask
  • Labels are stored with the same index as their corresponding task

Memory Management

Garbage Collection

The framework handles cleanup through several mechanisms:

  • Tasks are properly dereferenced when cleaned
  • Connections are explicitly disconnected
  • Objects are destroyed using their Destroy method
  • Threads are cancelled using task_cancel

Connection Handling

-- Clean connections first to prevent any pending events
for index, task in pairs(tasks) do
    if typeof(task) == "RBXScriptConnection" then
        task:Disconnect()
        tasks[index] = nil
        self._labels[index] = nil
    end
end

Debug System

Debug Mode

Debug mode is controlled through ReplicatedStorage:

local debug = ReplicatedStorage:FindFirstChild("Debug")
if debug and debug.Value then
    print("[Sweep Debug]", ...)
end

Debug Information

When enabled, the system logs:

  • Task creation and deletion
  • Memory usage (via gcinfo())
  • Stack traces for important operations
  • Task type information
  • Connection states
  • Thread states

Debug Logging

The debug system provides detailed logging for:

OperationInformation Logged
Task CreationTimestamp, task type, label
Task CleanupTimestamp, cleanup duration
Memory UsageCurrent memory usage, changes
Task ExecutionStart time, end time, duration
Connection StatesConnected, disconnected events
Thread ManagementThread creation, completion
Promise ResolutionResolution time, state

Advanced Usage

Custom Task Types

You can extend Sweep with custom task types:

local CustomTask = {}
CustomTask.__index = CustomTask

function CustomTask.new()
    return setmetatable({
        _cleanup = function() end
    }, CustomTask)
end

function CustomTask:Destroy()
    self._cleanup()
end

-- Usage with Sweep
local customTask = CustomTask.new()
sweep:GiveTask(customTask)

Promise Integration

The Promise integration handles different promise states:

function Sweep:GivePromise(promise)
    -- Return immediately if promise is already resolved
    if not promise:IsPending() then
        return promise
    end

    -- Create new promise that can be tracked
    local newPromise = promise.resolved(promise)
    local id = self:GiveTask(newPromise)

    -- Clean up automatically when promise completes
    newPromise:Finally(function()
        self[id] = nil
    end)

    return newPromise
end

Interval Task Implementation

function SweepTaskUtils.interval(interval, callback)
    local running = true
    local thread = task.spawn(function()
        while running do
            callback()
            task.wait(interval)
        end
    end)

    return function()
        running = false
        task.cancel(thread)
    end
end

Performance Considerations

Memory Usage

Optimize memory usage by cleaning up tasks as soon as they’re no longer needed.

Key considerations:

  • Each task requires minimal overhead (just table entries)
  • Labels add additional memory overhead per task
  • Debug mode increases memory usage due to logging

CPU Usage

Performance characteristics:

  • Task cleanup is performed sequentially
  • Connections are prioritized in cleanup
  • Interval tasks run on separate threads
  • Promise resolution is asynchronous

Best Practices

  1. Task Creation
-- Preferred: Single task for multiple operations
sweep:GiveTask(function()
    cleanup1()
    cleanup2()
    cleanup3()
end)

-- Avoid: Multiple individual tasks
sweep:GiveTask(cleanup1)
sweep:GiveTask(cleanup2)
sweep:GiveTask(cleanup3)
  1. Connection Management
-- Preferred: Group related connections
sweep:GiveTask(function()
    local conn1 = obj.Event1:Connect(handler1)
    local conn2 = obj.Event2:Connect(handler2)
    return function()
        conn1:Disconnect()
        conn2:Disconnect()
    end
end)
  1. Memory Optimization
-- Preferred: Clean unused tasks immediately
local taskId = sweep:GiveTask(heavyOperation)
-- ... use the operation ...
sweep[taskId] = nil  -- Clean up when done

Always use task labels in debug mode to track task lifecycles and identify potential memory leaks.