Skip to content

Array.permutations() performance #3

@ruslansennov

Description

@ruslansennov

@jest reported performance degradation of Array.permutations() in vavr:0.9.0. It seems the problem commit is 9e37950e2fa3113cba6fbcd03feebd1fc86ca1e1

Here is (slightly modified for testing) old code:

public static <T> Array<Array<T>> permOld(Array<T> array) {
    if (array.isEmpty()) {
        return Array.empty();
    } else {
        final Array<T> tail = array.tail();
        if (tail.isEmpty()) {
            return Array.of(array);
        } else {
            final Array<Array<T>> zero = Array.empty();
            return array.distinct().foldLeft(zero, (xs, x) -> {
                final Function<Array<T>, Array<T>> prepend = l -> l.prepend(x);
                return xs.appendAll(array.remove(x).permutations().map(prepend));
            });
        }
    }
}

And here is new code:

public static <T> Array<Array<T>> permNew(Array<T> array) {
    if (array.isEmpty()) {
        return Array.empty();
    } else {
        Array<Array<T>> results = Array.empty();
        for (T t : array.distinct()) {
            for (Array<T> ts : array.remove(t).permutations()) {
                results = results.append(Array.of(t).appendAll(ts));
            }
        }
        return results;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions