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.