Skip to content

Commit 5378c50

Browse files
committed
instruction_tree: Build source in PackedStringArray
From an efficiency point of view, repeatedly appending to an immutable string probably involves repeatedly copying the string. (Some languages have an optimisation where if `s` is the only reference to a string, then `s += "foo"` modifies `s` in place; I don't know if GDScript has that.) From a clarity perspective, it is strange for the output buffer to be an instance variable of the InstructionTree – it is a transient buffer used during a call to generate_text(). Replace it with a PackedStringArray, passed through the recursive calls, containing lines of code. Join it to produce the generated code as a whole.
1 parent ad75603 commit 5378c50

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed
Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
class_name InstructionTree
22
extends Object
33

4-
var out: String
5-
64

75
class TreeNode:
86
var data: String
@@ -17,19 +15,17 @@ class TreeNode:
1715

1816

1917
func generate_text(root_node: TreeNode, start_depth: int = 0) -> String:
20-
out = ""
21-
generate_text_recursive(root_node, start_depth)
22-
return out
18+
var out = PackedStringArray()
19+
generate_text_recursive(root_node, start_depth, out)
20+
return "".join(out)
2321

2422

25-
func generate_text_recursive(node: TreeNode, depth: int):
23+
func generate_text_recursive(node: TreeNode, depth: int, out: PackedStringArray):
2624
if node.data != "":
27-
for i in depth:
28-
out += "\t"
29-
out += node.data + "\n"
25+
out.append("\t".repeat(depth) + node.data + "\n")
3026

3127
for c in node.children:
32-
generate_text_recursive(c, depth + 1)
28+
generate_text_recursive(c, depth + 1, out)
3329

3430
if node.next:
35-
generate_text_recursive(node.next, depth)
31+
generate_text_recursive(node.next, depth, out)

0 commit comments

Comments
 (0)