How can caching be utilized to speed up the calculation of permutations in PHP?

Calculating permutations can be computationally expensive, especially for large sets of data. One way to speed up the calculation is by utilizing caching. By storing previously calculated permutations in a cache, we can retrieve them quickly instead of recalculating them each time.

function getPermutations($data) {
    $cacheKey = md5(json_encode($data));
    $cachedPermutations = apcu_fetch($cacheKey);

    if ($cachedPermutations !== false) {
        return $cachedPermutations;
    }

    $permutations = calculatePermutations($data);
    apcu_store($cacheKey, $permutations);

    return $permutations;
}

function calculatePermutations($data) {
    // Actual permutation calculation logic goes here
}

// Usage
$data = [1, 2, 3];
$permutations = getPermutations($data);