Use nested FOR loops for multi-level iteration Â
Nest FOR loops to perform operations across multiple collections simultaneously. This is particularly useful for creating relationships between all pairs of elements or processing hierarchical data structures.Nested loops are executed for every combination of elements from the outer and inner collections, resulting in a cartesian product of operations.
Be mindful of performance when using nested loops with large collections. The number of operations grows multiplicatively with collection sizes (N × M operations for two collections).
When using the SDKs or curling the endpoint, the query name must match what is defined in the
queries.hx file exactly.Example 1: Creating connections between all user pairs
Example 2: Cross-product operations with hierarchical data
Performance considerations
Nested loops can significantly impact performance:
- Two loops over collections of size N and M result in N × M operations
- Three nested loops result in N × M × P operations
- Consider using WHERE clauses to filter collections before looping
- For large datasets, evaluate whether nested loops are the most efficient approach
Tips for optimizing nested loops:
- Filter early: Apply WHERE clauses before entering loops to reduce iteration count
- Consider alternatives: Sometimes traversals or joins can be more efficient than nested loops
- Batch operations: Group related operations to minimize database calls
- Monitor performance: Test with realistic data volumes to identify bottlenecks