PSJ. - JSON Operations

<< Click to Display Table of Contents >>

Navigation:  3. Script Language > JSON - Parser > Parser-Operations > !Utility and Conversion >

PSJ. - JSON Operations

PSJ.Compact

Previous Top Next


SPR Script Language

 

PSJ.Compact

Performs memory compaction on the internal node arrays to remove fragmentation.

 

Intention

 

When you delete nodes from a JSON document using commands like PSJ.DelKey or PSJ.FreeTree, the library marks the memory slots as free but does not immediately shrink the memory arrays. This can lead to fragmentation, where the internal node count (reported by PSJ.GetNodeCount) remains high even if few nodes are actually in use.

 

The PSJ.Compact command rebuilds the internal arrays to remove these empty slots, reducing the memory footprint and resetting the node count to the actual number of active nodes. While the library automatically calls this function internally after a certain number of deletions, you can call it manually to force an immediate optimization, which is useful in long-running scripts with heavy JSON manipulation.

 

Syntax

 

PSJ.Compact[|$$RET]

 

Parameter Explanation

 

P1 - $$RET - (Variable, Numeric, Optional)

An optional variable to store the result code. The command returns 0 (%JSON_ERR_NONE) on success.

 

Examples

 

'***********************************

' PSJ.Compact - Sample 1: Manual Memory Optimization

'***********************************

VAR.$$JSN={"a":1,"b":2,"c":3,"d":4}

PSJ.Parse|$$JSN|$$H_1

 

PSJ.GetNodeCount|$$CNT

PRT.Node count before deletions: $$CNT

 

' Delete two keys

PSJ.DelKey|$$H_1|b

PSJ.DelKey|$$H_1|d

 

PSJ.GetNodeCount|$$CNT

PRT.Node count after deletions (unchanged high-water mark): $$CNT

 

' Force compaction

PSJ.Compact|$$RES

JNZ.$$RES|Lab_failed

 

PSJ.GetNodeCount|$$CNT

PRT.Node count after compaction: $$CNT

 

PSJ.Free|$$H_1

END.

 

 

Remarks

 

- The JSON library automatically calls the internal compaction function whenever a new node is created and the number of freed nodes has reached a certain threshold (e.g., 1000). Therefore, manual calls to PSJ.Compact are typically only needed in scripts that perform a very large number of deletions without subsequent additions, and where minimizing memory usage at a specific moment is critical.

- Compaction is a relatively expensive operation as it involves rebuilding the internal arrays and updating all parent/child/document references. It should not be called inside tight loops.

 

See also:

 

PSJ.GetNodeCount

PSJ.FreeTree

PSJ.DelElem