Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

Improve object custom iterator performance by removing Array allocations

aurpine600a18e2ae69
diff --git a/doc/classes/Object.xml b/doc/classes/Object.xml
index bc340f6a22c..6aa60fad3c8 100644
--- a/doc/classes/Object.xml
+++ b/doc/classes/Object.xml
@@ -212,7 +212,7 @@
<return type="bool" />
<param index="0" name="iter" type="Array" />
<description>
- Initializes the iterator. [param iter] stores the iteration state. Since GDScript does not support passing arguments by reference, a single-element array is used as a wrapper. Returns [code]true[/code] so long as the iterator has not reached the end.
+ Initializes the iterator. [param iter] stores the iteration state. Since GDScript does not support passing arguments by reference, a single-element array is used as a wrapper. This array should not be resized. Returns [code]true[/code] so long as the iterator has not reached the end.
[codeblock]
class MyRange:
var _from
@@ -247,7 +247,7 @@
<return type="bool" />
<param index="0" name="iter" type="Array" />
<description>
- Moves the iterator to the next iteration. [param iter] stores the iteration state. Since GDScript does not support passing arguments by reference, a single-element array is used as a wrapper. Returns [code]true[/code] so long as the iterator has not reached the end.
+ Moves the iterator to the next iteration. [param iter] stores the iteration state. Since GDScript does not support passing arguments by reference, a single-element array is used as a wrapper. This array should not be resized. Returns [code]true[/code] so long as the iterator has not reached the end.
</description>
</method>
<method name="_notification" qualifiers="virtual">
diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp
index b470b15872f..b8a2d2a2bbe 100644
--- a/modules/gdscript/gdscript_vm.cpp
+++ b/modules/gdscript/gdscript_vm.cpp
@@ -3348,7 +3348,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
OPCODE(OPCODE_ITERATE_BEGIN_OBJECT) {
CHECK_SPACE(4);
- GET_VARIANT_PTR(counter, 0);
+ GET_VARIANT_PTR(state, 0);
GET_VARIANT_PTR(container, 1);
#ifdef DEBUG_ENABLED
@@ -3365,20 +3365,16 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
Object *obj = *VariantInternal::get_object(container);
#endif
- *counter = Variant();
- Array ref = { *counter };
- Variant vref;
- VariantInternal::initialize(&vref, Variant::ARRAY);
- *VariantInternal::get_array(&vref) = ref;
-
- const Variant *args[] = { &vref };
+ Array ref = { Variant() };
+ VariantInternal::initialize(state, Variant::ARRAY);
+ *VariantInternal::get_array(state) = ref;
Callable::CallError ce;
- Variant has_next = obj->callp(CoreStringName(_iter_init), args, 1, ce);
+ Variant has_next = obj->callp(CoreStringName(_iter_init), const_cast<const Variant **>(&state), 1, ce);
#ifdef DEBUG_ENABLED
if (ref.size() != 1 || ce.error != Callable::CallError::CALL_OK) {
- err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type %s.)", *container);
+ err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type "%s".)", GDScript::debug_get_script_name(obj->get_script_instance()->get_script()));
OPCODE_BREAK;
}
#endif
@@ -3387,13 +3383,13 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
ip = jumpto;
} else {
- *counter = ref[0];
+ Variant *state_ptr = &(ref[0]);
GET_VARIANT_PTR(iterator, 2);
- *iterator = obj->callp(CoreStringName(_iter_get), (const Variant **)&counter, 1, ce);
+ *iterator = obj->callp(CoreStringName(_iter_get), const_cast<const Variant **>(&state_ptr), 1, ce);
#ifdef DEBUG_ENABLED
if (ce.error != Callable::CallError::CALL_OK) {
- err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container);
+ err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type "%s".)", GDScript::debug_get_script_name(obj->get_script_instance()->get_script()));
OPCODE_BREAK;
}
#endif
@@ -3715,7 +3711,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
OPCODE(OPCODE_ITERATE_OBJECT) {
CHECK_SPACE(4);
- GET_VARIANT_PTR(counter, 0);
+ GET_VARIANT_PTR(state, 0);
GET_VARIANT_PTR(container, 1);
#ifdef DEBUG_ENABLED
@@ -3732,19 +3728,12 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
Object *obj = *VariantInternal::get_object(container);
#endif
- Array ref = { *counter };
- Variant vref;
- VariantInternal::initialize(&vref, Variant::ARRAY);
- *VariantInternal::get_array(&vref) = ref;
-
- const Variant *args[] = { &vref };
-
Callable::CallError ce;
- Variant has_next = obj->callp(CoreStringName(_iter_next), args, 1, ce);
+ Variant has_next = obj->callp(CoreStringName(_iter_next), const_cast<const Variant **>(&state), 1, ce);
#ifdef DEBUG_ENABLED
- if (ref.size() != 1 || ce.error != Callable::CallError::CALL_OK) {
- err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type %s.)", *container);
+ if (VariantInternal::get_array(state)->size() != 1 || ce.error != Callable::CallError::CALL_OK) {
+ err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type "%s".)", GDScript::debug_get_script_name(obj->get_script_instance()->get_script()));
OPCODE_BREAK;
}
#endif
@@ -3753,13 +3742,14 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
ip = jumpto;
} else {
- *counter = ref[0];
+ // For _iter_get(): get a pointer to the single element in the array.
+ Variant *state_ptr = &((*VariantInternal::get_array(state))[0]);
GET_VARIANT_PTR(iterator, 2);
- *iterator = obj->callp(CoreStringName(_iter_get), (const Variant **)&counter, 1, ce);
+ *iterator = obj->callp(CoreStringName(_iter_get), const_cast<const Variant **>(&state_ptr), 1, ce);
#ifdef DEBUG_ENABLED
if (ce.error != Callable::CallError::CALL_OK) {
- err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container);
+ err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type "%s".)", GDScript::debug_get_script_name(obj->get_script_instance()->get_script()));
OPCODE_BREAK;
}
#endif
diff --git a/modules/gdscript/tests/scripts/runtime/errors/for_loop_iterator_array_size.gd b/modules/gdscript/tests/scripts/runtime/errors/for_loop_iterator_array_size.gd
new file mode 100644
index 00000000000..bf284b2f58a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/runtime/errors/for_loop_iterator_array_size.gd
@@ -0,0 +1,94 @@
+func iterate(v: Variant):
+ for i in v:
+ print(i)
+
+class BadInit:
+ # Whether to push or pop during init
+ var push
+
+ func _init(new_push):
+ push = new_push
+
+ func _iter_init(iter: Array):
+ if push:
+ iter.push_back("hi")
+ else:
+ iter.pop_back()
+ return true
+
+ func _iter_next(iter: Array):
+ iter.pop_back()
+ return !iter.is_empty()
+
+ func _iter_get(iter):
+ return iter
+
+func subtest_init_array_large():
+ print("SUBTEST_INIT_ARRAY_LARGE")
+ for i in BadInit.new(true):
+ print(i)
+
+func subtest_init_array_empty():
+ print("SUBTEST_INIT_ARRAY_EMPTY")
+ for i in BadInit.new(false):
+ print(i)
+
+func subtest_variant_init_array_large():
+ print("SUBTEST_VARIANT_INIT_ARRAY_LARGE")
+ iterate(BadInit.new(true))
+
+func subtest_variant_init_array_empty():
+ print("SUBTEST_VARIANT_INIT_ARRAY_EMPTY")
+ iterate(BadInit.new(false))
+
+class BadNext:
+ var push: bool
+
+ func _init(new_push):
+ push = new_push
+
+ func _iter_init(iter: Array):
+ iter[0] = 1
+ return true
+
+ func _iter_next(iter: Array):
+ if push:
+ iter.push_back(2)
+ else:
+ iter.pop_back()
+ return true
+
+ func _iter_get(iter):
+ return iter
+
+func subtest_next_array_large():
+ print("SUBTEST_NEXT_ARRAY_LARGE")
+ for i in BadNext.new(true):
+ print(i)
+
+func subtest_next_array_empty():
+ print("SUBTEST_NEXT_ARRAY_EMPTY")
+ for i in BadNext.new(false):
+ print(i)
+
+func subtest_variant_next_array_large():
+ print("SUBTEST_VARIANT_NEXT_ARRAY_LARGE")
+ iterate(BadNext.new(true))
+
+func subtest_variant_next_array_empty():
+ print("SUBTEST_VARIANT_NEXT_ARRAY_EMPTY")
+ iterate(BadNext.new(false))
+
+
+func test():
+ # Typed
+ subtest_init_array_large()
+ subtest_init_array_empty()
+ subtest_next_array_large()
+ subtest_next_array_empty()
+
+ # Untyped
+ subtest_variant_init_array_large()
+ subtest_variant_init_array_empty()
+ subtest_variant_next_array_large()
+ subtest_variant_next_array_empty()
diff --git a/modules/gdscript/tests/scripts/runtime/errors/for_loop_iterator_array_size.out b/modules/gdscript/tests/scripts/runtime/errors/for_loop_iterator_array_size.out
new file mode 100644
index 00000000000..ef211d61ac8
--- /dev/null
+++ b/modules/gdscript/tests/scripts/runtime/errors/for_loop_iterator_array_size.out
@@ -0,0 +1,21 @@
+GDTEST_RUNTIME_ERROR
+SUBTEST_INIT_ARRAY_LARGE
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:28 on subtest_init_array_large(): There was an error calling "_iter_next" on iterator object of type "BadInit".
+SUBTEST_INIT_ARRAY_EMPTY
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:33 on subtest_init_array_empty(): There was an error calling "_iter_next" on iterator object of type "BadInit".
+SUBTEST_NEXT_ARRAY_LARGE
+1
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:67 on subtest_next_array_large(): There was an error calling "_iter_next" on iterator object of type "BadNext".
+SUBTEST_NEXT_ARRAY_EMPTY
+1
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:72 on subtest_next_array_empty(): There was an error calling "_iter_next" on iterator object of type "BadNext".
+SUBTEST_VARIANT_INIT_ARRAY_LARGE
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:2 on iterate(): Unable to iterate on object of type 'Object'.
+SUBTEST_VARIANT_INIT_ARRAY_EMPTY
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:2 on iterate(): Unable to iterate on object of type 'Object'.
+SUBTEST_VARIANT_NEXT_ARRAY_LARGE
+1
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:3 on iterate(): Unable to iterate on object of type 'Object' (type changed since first iteration?).
+SUBTEST_VARIANT_NEXT_ARRAY_EMPTY
+1
+>> SCRIPT ERROR at runtime/errors/for_loop_iterator_array_size.gd:3 on iterate(): Unable to iterate on object of type 'Object' (type changed since first iteration?).
diff --git a/modules/gdscript/tests/scripts/runtime/features/for_loop_iterator_object.gd b/modules/gdscript/tests/scripts/runtime/features/for_loop_iterator_object.gd
new file mode 100644
index 00000000000..3e8872a4ff1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/runtime/features/for_loop_iterator_object.gd
@@ -0,0 +1,102 @@
+# Tests custom iterator correctness both typed and untyped.
+
+class ExponentialIterator:
+ var base: int
+ var end: int
+
+ func _init(new_base: int, new_end: int):
+ self.base = new_base
+ self.end = new_end
+
+ func _iter_init(iter: Array):
+ iter[0] = 1
+ return iter[0] < end
+
+ func _iter_next(iter: Array):
+ iter[0] *= base
+ return iter[0] < end
+
+ func _iter_get(iter: Variant):
+ return iter
+
+
+@warning_ignore_start("unsafe_method_access")
+class StringIterator:
+ var s: String
+
+ func _init(value: String):
+ self.s = value
+
+ func _iter_init(iter: Array):
+ iter[0] = s
+ return !iter[0].is_empty()
+
+ func _iter_next(iter: Array):
+ iter[0] = iter[0].substr(1)
+ return !iter[0].is_empty()
+
+ func _iter_get(iter: Variant):
+ return iter.left(1)
+
+
+func iterate_variant(v: Variant, break_condition: Callable = Callable()):
+ for i in v:
+ if break_condition.is_valid() and break_condition.call(i):
+ break
+ print(i)
+
+
+func iterate_variant_nested(a: Variant, b: Variant, break_condition: Callable = Callable()):
+ for i in a:
+ for j in b:
+ if break_condition.is_valid() and break_condition.call(i, j):
+ break
+ print(i, j)
+
+
+func test():
+ print("Test typed exp 2,16")
+ for i in ExponentialIterator.new(2, 17):
+ print(i)
+
+ print("Test variant exp 2,16")
+ iterate_variant(ExponentialIterator.new(2, 17))
+
+ print("Test typed exp -3,-27")
+ for i in ExponentialIterator.new(-3, 30):
+ print(i)
+
+ print("Test typed exp -3,-27")
+ iterate_variant(ExponentialIterator.new(-3, 30))
+
+ print("Test typed nested same str iterator")
+ var si := StringIterator.new("abc")
+ for i in si:
+ for j in si:
+ print(i, j)
+
+ print("Test nested variant same str iterator")
+ iterate_variant_nested(si, si)
+
+ print("Test break from typed str")
+ for i in StringIterator.new("world"):
+ if i in "hello":
+ break
+ print(i)
+
+ print("Test break from variant str")
+ iterate_variant(StringIterator.new("world"), func(i): return i in "hello")
+
+ print("Test break from nested diff typed")
+ for i: String in StringIterator.new("a2z"):
+ for j in ExponentialIterator.new(2, 100):
+ if j > ord(i):
+ break
+ print(i, j)
+
+ print("Test break from nested diff variant")
+ iterate_variant_nested(
+ StringIterator.new("a2z"),
+ ExponentialIterator.new(2, 100),
+ func(i: String, j): return j > ord(i)
+ )
diff --git a/modules/gdscript/tests/scripts/runtime/features/for_loop_iterator_object.out b/modules/gdscript/tests/scripts/runtime/features/for_loop_iterator_object.out
new file mode 100644
index 00000000000..f13db1be6f7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/runtime/features/for_loop_iterator_object.out
@@ -0,0 +1,89 @@
+GDTEST_OK
+Test typed exp 2,16
+1
+2
+4
+8
+16
+Test variant exp 2,16
+1
+2
+4
+8
+16
+Test typed exp -3,-27
+1
+-3
+9
+-27
+Test typed exp -3,-27
+1
+-3
+9
+-27
+Test typed nested same str iterator
+aa
+ab
+ac
+ba
+bb
+bc
+ca
+cb
+cc
+Test nested variant same str iterator
+aa
+ab
+ac
+ba
+bb
+bc
+ca
+cb
+cc
+Test break from typed str
+w
+Test break from variant str
+w
+Test break from nested diff typed
+a1
+a2
+a4
+a8
+a16
+a32
+a64
+21
+22
+24
+28
+216
+232
+z1
+z2
+z4
+z8
+z16
+z32
+z64
+Test break from nested diff variant
+a1
+a2
+a4
+a8
+a16
+a32
+a64
+21
+22
+24
+28
+216
+232
+z1
+z2
+z4
+z8
+z16
+z32
+z64