Skip to content

Excessive Calls Optimization Summary

Problem Identified

The profiling revealed excessive function calls: - 1,531,201 hasattr() calls for 10,000 resources (153 per resource!) - 514,092 resolve_value() recursive calls (51 per resource)

Root Causes Found

  1. resolve_value(): Was checking EVERY value with hasattr(value, "_is_runtime_value"), including:
  2. 40,064 calls on None values
  3. 6,006 calls on strings
  4. 4,018 calls on dicts

  5. _check_value_for_cross_refs(): Similar pattern, checking every value including primitives

  6. S3 Bucket configs have ~28 attributes, many are None, all were being checked recursively

Solution Implemented

1. Early Return for Primitive Types

Created a frozenset of primitive types that can NEVER have runtime values:

_PRIMITIVE_TYPES = frozenset(
    {
        type(None),
        bool,
        int,
        float,
        str,
        bytes,
        complex,
        type,
        type(Ellipsis),
        type(NotImplemented),
    }
)

2. Type Check Before hasattr()

def resolve_value(value, context):
    # Old approach
    if hasattr(value, "_is_runtime_value"):  # Called on EVERY value
        return value.resolve(context)
    return value


def resolve_value(value, context):
    # New approach
    value_type = type(value)
    if value_type in _PRIMITIVE_TYPES:  # Fast set lookup
        return value  # Skip hasattr() entirely!
    return value.resolve(context)

3. Skip None Values in Collections

When recursing through dicts/lists, skip None values:

for k, v in value.items():
    if v is not None:  # Skip the most common empty value
        self._check_value_for_cross_refs(f"{path}.{k}", v, current_stack)

Results

hasattr() Calls Reduced by 49%

  • Before: 150,728 calls (15.1 per resource)
  • After: 76,638 calls (7.7 per resource)
  • Eliminated:
  • 40,064 calls on None
  • 20,000 calls on None for cross-stack checks
  • Most calls on str/dict primitives

Performance Improvement

  • Synthesis speed: 24,893 → 26,031 resources/second (4.5% faster)
  • Total time: 0.40s → 0.38s for 10,000 resources

Key Insights

  1. Defensive programming can be expensive - Checking every value recursively adds up
  2. None is everywhere - Resource configs have many None values (unset attributes)
  3. Simple type checks are fast - type(value) in frozenset is much faster than hasattr()
  4. Most values are primitives - In typical configs, 80%+ of values are primitives

Future Optimizations

The remaining 76,638 hasattr() calls are mostly: - 54,074 on logging internals (_local.logging_disabled/min_level) - 22,564 on actual objects that might have attributes

Further gains could come from: 1. Caching logging state checks 2. Using dict lookups instead of hasattr() where possible 3. Batching or memoizing common patterns