Import
SharedArray
SharedArray is an array-like object that shares underlying memory between VUs. The constructor function executes only once, and its result is saved in memory once. When a script requests an element, k6 gives a copy of that element.string
required
A unique name for the SharedArray. Used to identify it across VUs.
function
required
A function that returns an array. This function executes only once during initialization.
- Getting length with
length - Getting elements by index:
array[index] - Using
for-ofloops
Basic Example
Loading JSON Data
Filtering Data
Common Pitfalls
Avoid array methods that create new arrays
Avoid array methods that create new arrays
Methods like Do:
.filter() and .map() create regular arrays when called on a SharedArray, removing memory benefits.Don’t:Performance Characteristics
Internally, SharedArray keeps data marshaled as JSON and unmarshals elements only when requested. This operation is typically unnoticeable relative to other operations, but for small data sets, SharedArray might perform worse. Memory savings:- 100-1000 elements: Minimal benefit
- 10,000+ elements: Significant memory and CPU savings
- 100,000+ elements: Dramatic improvement (8-9GB → 238-275MB in tests)
SharedArray is most beneficial for large datasets. For small datasets (< 1000 items), the overhead might outweigh the benefits.
Use Cases
- Loading test data from large JSON/CSV files
- Sharing user credentials across VUs
- Distributing test scenarios or configurations
- Reusing API payloads without duplication
SharedArray is read-only after construction. You cannot use it to communicate data between VUs during test execution.