Cache array length in for-in-array loop if possible

If the range expression is not a local variable (which can be updated in
the loop body affecting loop behavior, see KT-21354), we can cache the
array length, thus turning a for-in-array loop into a simple optimizable
counter loop.

 #KT-21321 In Progress
This commit is contained in:
Dmitry Petrov
2017-11-24 17:46:54 +03:00
parent 328c67b9e8
commit e2fa613b70
10 changed files with 127 additions and 15 deletions
@@ -21,7 +21,7 @@ fun box() {
}
// METHOD : UnderscoreNamesKt$box$1.invoke(LA;Ljava/lang/String;I)Ljava/lang/String;
// VARIABLE : NAME=q TYPE=Ljava/lang/String; INDEX=15
// VARIABLE : NAME=q TYPE=Ljava/lang/String; INDEX=16
// VARIABLE : NAME=d TYPE=C INDEX=11
// VARIABLE : NAME=_ TYPE=Ljava/lang/String; INDEX=10
// VARIABLE : NAME=c TYPE=C INDEX=9
@@ -0,0 +1,12 @@
// WITH_RUNTIME
var xs = intArrayOf(1, 2, 3)
fun box(): String {
var sum = 0
for (x in xs) {
sum = sum * 10 + x
xs = IntArray(0)
}
return if (sum == 123) "OK" else "Fail: $sum"
}
@@ -0,0 +1,23 @@
// WITH_RUNTIME
// IGNORE_BACKEND: JS
// In Kotlin 1.0, in a for-in-array loop, range expression is cached in
// a local variable unless it is already a local variable.
// This caused the following quirky behavior:
// if an array variable is updated in the loop body, it affects the loop
// execution (see https://youtrack.jetbrains.com/issue/KT-21354).
// Most likely it is a bug, however, fixing it right now is a breaking
// change requiring a proper deprecation loop.
// When the design decision is made, it might be required to update this
// test (e.g., by adding a proper LANGUAGE_VERSION directive).
// Note that JS back-end handles this case "correctly".
fun box(): String {
var xs = intArrayOf(1, 2, 3)
var sum = 0
for (x in xs) {
sum = sum * 10 + x
xs = intArrayOf(4, 5)
}
return if (sum == 15) "OK" else "Fail: $sum"
}