When the speed of code is an important consideration, Kotlin provides utility functions for profiling code performance: measureNanoTime and measureTimeInMillis. Both functions accept a lambda as their argument and measure the execution speed of the code contained within the lambda. measureNanoTime returns a time in nanoseconds, and measureTimeInMillis returns a time in milliseconds.
Wrap the function to measure in one of the utility functions like so:
val listInNanos = measureNanoTime { // List functional chain here } val sequenceInNanos = measureNanoTime { // Sequence functional chain here } println("List completed in $listInNanos ns") println("Sequence completed in $sequenceInNanos ns")
As an experiment, try profiling the performance of the list and sequence versions of the prime number examples. (Change the list example to check numbers through 7,919 so that it can find 1,000 primes.) How much does the change from a list to a sequence affect the performance time?