I received a lint message while writing Kotlin using IntelliJ as my IDE: The argument can be converted to 'Set' to improve performance
My code went something like this:
val variable3 = variable1 - variable2 variables are of type List<Int>
The linter recommended me to change it to val variable3 = variable1 - variable2.toSet()
I would like to find out why it recommends this change and where the documentation is so next time I can look up the messages and learn the reasoning behind the lint check.
CodePudding user response:
You can hover over and open the documentation like this:
The general quick fix options can be found and turn on/off under settings -> inspections -> kotlin (example)
CodePudding user response:
This is about performance and efficiency — in particular, about how the performance scales as your data gets bigger.
The - operator calls the standard library's Iterable<T>.minus(elements: Iterable<T>) extension function. If you look at its code (which you can do in IntelliJ), you'll see that that works by taking the first iterable (variable1 in this case) and filtering it to keep only the values not in the second one (variable2).
How does it check whether an element is in the second one? By calling its contains() method. But how that works will depend on the type of iterable. Most Sets, for example, can look up by hash code, which takes a short time, regardless of how big the set is.
However, most Lists and other iterables can't do that: they need to search through the whole list, element by element. How long that takes will obviously depend on the size of the list — it'll be very quick for short lists, but it might take some time to search through a list with thousands or millions of elements.
What makes it particularly important in this case is that it has to do that search repeatedly: once for each element of the first one. So the time can really mount up.
Say that the first iterable has
