Skip to content

Commit 2b9d539

Browse files
roookeeeNico HellerCalinou
authored
C#: Avoid accessing expensive properties of Godot C# objects multiple times if possible (#6408)
Co-authored-by: Nico Heller <nheller@uni-bremen.de> Co-authored-by: Hugo Locurcio <hugo.locurcio@hugo.pro>
1 parent bd428d5 commit 2b9d539

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

tutorials/scripting/c_sharp/c_sharp_basics.rst

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,48 @@ the performance of C# in Godot — while generally in the same order of magnitud
292292
— is roughly **~4×** that of GDScript in some naive cases. C++ is still
293293
a little faster; the specifics are going to vary according to your use case.
294294
GDScript is likely fast enough for most general scripting workloads.
295-
C# is faster, but requires some expensive marshalling when talking to Godot.
295+
296+
Most properties of Godot C# objects that are based on ``Godot.Object``
297+
(e.g. any ``Node`` like ``Control`` or ``Node3D`` like ``Camera3D``) require native (interop) calls as they talk to
298+
Godot's C++ core.
299+
Consider assigning values of such properties into a local variable if you need to modify or read them multiple times at
300+
a single code location:
301+
302+
.. code-block:: csharp
303+
304+
using Godot;
305+
using System;
306+
307+
public class YourCustomClass : Node3D
308+
{
309+
private void ExpensiveReposition()
310+
{
311+
for (var i = 0; i < 10; i++)
312+
{
313+
// Position is read and set 10 times which incurs native interop.
314+
// Furthermore the object is repositioned 10 times in 3D space which takes additional time.
315+
Position += new Vector3(i, i);
316+
}
317+
}
318+
319+
private void Reposition()
320+
{
321+
// A variable is used to avoid native interop for Position on every loop.
322+
var newPosition = Position;
323+
for (var i = 0; i < 10; i++)
324+
{
325+
newPosition += new Vector3(i, i);
326+
}
327+
// Setting Position only once avoids native interop and repositioning in 3D space.
328+
Position = newPosition;
329+
}
330+
}
331+
332+
Passing raw arrays (such as ``byte[]``) or ``string`` to Godot's C# API requires marshalling which is
333+
comparatively pricey.
334+
335+
The implicit conversion from ``string`` to ``NodePath`` or ``StringName`` incur both the native interop and marshalling
336+
costs as the ``string`` has to be marshalled and passed to the respective native constructor.
296337

297338
Using NuGet packages in Godot
298339
-----------------------------

0 commit comments

Comments
 (0)