0

Is there some kind of compile-time optimization for code similar to this. Or is the complexity of the entire execution the same ass the complexity of each function?

If yes what's the best way to go about analyzing the performance of code like this? If yes are they documented somewhere?

    values
        .map { it.someKey }
        .distinct()
        .sorted()
        .fold(ArrayList()) { list, some ->
            return newList
        }
aryaxt
  • 76,198
  • 92
  • 293
  • 442

1 Answers1

0

You can find time complexity with simple analyses. For example, I think (don't quote me on this) that the lower bound of distinct is O(n log n), which makes the time complexity of your program also O(n log n).

For actual benchmarking, though, you should read this post on java microbenchmarking

As for compiler optimizations, we can actually try that ourselves.

Here's a code segment similar to the one you wrote:

fun test(values :List<Test>): String {
    return values
        .map { it.someValue }
        .distinct()
        .sorted()
        .fold("") {a,b -> a + b }
}

Plug it into intellij's compiler and decompiler, into Java, and we get

public final String test(@NotNull List values) {
    Intrinsics.checkParameterIsNotNull(values, "values");
    Iterable $this$fold$iv = values;
    Collection destination$iv$iv = new ArrayList(CollectionsKt.collectionSizeOrDefault($this$fold$iv, 10));
    Iterator var7 = $this$fold$iv.iterator();

    boolean var10;
    while(var7.hasNext()) {
        Object item$iv$iv = var7.next();
        Test it = (Test)item$iv$iv;
        var10 = false;
        String var12 = it.getSomeValue();
        destination$iv$iv.add(var12);
    }

    $this$fold$iv = (Iterable)CollectionsKt.sorted((Iterable)CollectionsKt.distinct((Iterable)((List)destination$iv$iv)));
    Object initial$iv = "";
    Object accumulator$iv = initial$iv;

    String b;
    for(Iterator var15 = $this$fold$iv.iterator(); var15.hasNext(); accumulator$iv = accumulator$iv + b) {
        Object element$iv = var15.next();
        b = (String)element$iv;
    }

    return accumulator$iv;
}

And you can see how the Kotlin compiler has inlined different methods, which speeds up performance.

Carson Graham
  • 519
  • 4
  • 15