Rule: Boolean expression using in
/ !in
for progression
#3824
-
It appears boolean expressions such as the condition of an fun main(args: Array<String>) {
val x = args[0].toInt()
val start = args[1].toInt()
val end = args[2].toInt()
if (x in start..end step 2) {
println("in")
}
} The byte code this generates (Kotlin 1.5.0, JVM target) is pretty inefficient:
So it apparently:
Therefore (if I understand it correctly), until the first matching element is found for every element in the progression it would wrap the primitive in an object and then compare it. (Note that this is only for boolean expressions; However, I am not sure how relevant a rule for this is because I don't think such code would be pretty common. That is why I have created a discussion for this for now; feedback is appreciated. Maybe the bug here is also that the Kotlin compiler is not emitting optimized byte code, e.g. it could probably write: if (x >= start && x <= end && (x - start % step == 0)) {
// ...
} (Though maybe since this usecase is so uncommon such feature was not added to the compiler.) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Thanks for the proposal. I'm unsure if we want to start going in this direction and adding rules for missed compiler optimizations. I would try to keep Detekt a higher level and inspect readability/code-quality issues or obvious performance problems. IMHO for this specific rule using an |
Beta Was this translation helpful? Give feedback.
Thanks for the proposal. I'm unsure if we want to start going in this direction and adding rules for missed compiler optimizations.
I would try to keep Detekt a higher level and inspect readability/code-quality issues or obvious performance problems.
IMHO for this specific rule using an
IntProgression
is actually way more readable than having to manually write the equivalent boolean condition.