클래스 속성에 대한 캐시를 구현하는 방법은 무엇인가요?

예를 들어, Python에서는 @property 데코레이터와 @cached_property 데코레이터를 사용하여 캐시를 구현할 수 있습니다. @property 데코레이터는 클래스 속성을 getter 메서드로 변환하고, @cached_property 데코레이터는 캐시를 추가하여 속성 값을 저장하고 필요한 경우에만 계산합니다.

아래는 @cached_property 데코레이터를 사용한 간단한 예제입니다:

class MyClass:
    def __init__(self):
        self._cached_result = None

    @cached_property
    def my_property(self):
        if self._cached_result is None:
            # Calculate the property value
            self._cached_result = expensive_calculation()
        return self._cached_result

위의 예제에서 my_property는 클래스 속성이 아닌 getter 메서드로 변환되었고, _cached_result 변수를 사용하여 캐시 값을 저장합니다. my_property가 호출될 때마다 캐시된 값이 존재하면 그 값을 반환하고, 캐시된 값이 없을 경우 계산하여 저장합니다.

이러한 방식으로 클래스 속성에 캐시를 구현하면 속성 값을 한 번만 계산하고 필요할 때마다 캐시된 값을 사용할 수 있어 성능을 향상시킬 수 있습니다.


참고 자료: