Unsafe sequence operations
Factor handbook » The language » Collections » Sequence operations

Prev:Control flow with sequences
Next:Implementing sequence combinators


The nth-unsafe and set-nth-unsafe sequence protocol bypasses bounds checks for increased performance.

These words assume the sequence index given is within bounds; if it is not, memory corruption can occur. Great care must be exercised when using these words. First, make sure the code in question is actually a bottleneck; next, try improving the algorithm first. If all else fails, then the unsafe sequence words can be used.

There is a very important invariant these word must preserve: if at some point in time, the length of a sequence was n, then any future lookups of elements with indices below n must not crash the VM, even if the sequence length is now less than n. For example, vectors preserve this invariant by never shrinking the underlying storage, only growing it as necessary.

The justification for this is that the VM should not crash if a resizable sequence is resized during the execution of an iteration combinator.

Indeed, iteration combinators are the primary use-case for these words; if the iteration index is already guarded by a loop test which ensures it is within bounds, then additional bounds checks are redundant. For example, see the implementation of each.