Skip to content

Commit 33a24b1

Browse files
EmandMsmitdylan2001netcode-ci-service
authored
chore: Small performance improvements (#3683)
## Purpose of this PR @smitdylan2001 found and fixed some small performance improvements, which do not change any functionality. Especially the position and rotation calls and LINQ call removals are very helpful for performance 1. Merge looped `Add` calls on `List<T>` variables into `AddRange` - `AddRange` will ensure the list is only extended once. 2. Optimize empty string checks - Comparing strings using `String.Length` is faster than using `Equals` ([C# docs reference](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1820?view=vs-2022#rule-description:~:text=Comparing%20strings%20using%20the%20String.Length%20property%20or%20the%20String.IsNullOrEmpty%20method%20is%20faster%20than%20using%20Equals)) 3. Merge position & rotation calls into one - `SetPositionAndRotation` has a small performance improvement ([docs](https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Transform.SetPositionAndRotation.html#:~:text=When%20setting%20both%20the%20position%20and%20rotation%20of%20a%20transform%2C%20calling%20this%20method%20is%20more%20efficient%20than%20assigning%20to%20Transform.position%20and%20Transform.rotation%20individually.)) 4. Short circuit operators for bools - We had a couple of places that were using bytewise operations on boolean properties. This fixes them. 5. Use native Count instead of LINQ - `.Count()` uses LINQ and has a cost. `.Count` does the same thing without the LINQ cost. 6. Use `StringBuilder.AppendJoin` rather than `StringBuilder.Append(String.Join` continues: #3680 ## Jira ticket n/a: contribution from external user ### Changelog - Changed: made many very small performance improvements. ## Documentation - Updated the scripting in the docs to use `SetPositionAndRotation` rather than setting the two independently ## Testing & QA (How your changes can be verified during release Playtest) - These do not change functionality. Automated testing should catch any compiler errors. _Does the change require QA team to:_ - [ ] `Review automated tests`? - [ ] `Execute manual tests`? - [ ] `Provide feedback about the PR`? If any boxes above are checked the QA team will be automatically added as a PR reviewer. ## Backports These are small performance improvements so they do not need to be backported. --------- Co-authored-by: Dylan Smit <[email protected]> Co-authored-by: Unity Netcode CI <[email protected]>
1 parent 5f16181 commit 33a24b1

34 files changed

+68
-148
lines changed

Examples/CharacterControllerMovingBodies/Assets/Scripts/MoverScriptNoRigidbody.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,7 @@ protected override void OnNetworkPreSpawn(ref NetworkManager networkManager)
136136

137137
/// <summary>
138138
/// We are using post spawn to handle any final spawn initializations.
139-
/// At this point we know all NetworkBehaviours on this instance has
140-
/// been spawned.
139+
/// At this point we know all NetworkBehaviours on this instance have been spawned.
141140
/// </summary>
142141
protected override void OnNetworkPostSpawn()
143142
{
@@ -173,8 +172,7 @@ public override void OnNetworkDespawn()
173172
{
174173
m_CharacterController.enabled = false;
175174
Camera.main.transform.SetParent(null, false);
176-
Camera.main.transform.position = m_CameraOriginalPosition;
177-
Camera.main.transform.rotation = m_CameraOriginalRotation;
175+
Camera.main.transform.SetPositionAndRotation(m_CameraOriginalPosition, m_CameraOriginalRotation);
178176
}
179177
base.OnNetworkDespawn();
180178
}

Examples/OverridingScenesAndPrefabs/Assets/Scripts/MoverScriptNoRigidbody.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
using Random = UnityEngine.Random;
66
using Debug = UnityEngine.Debug;
77

8-
#region MoverScriptNoRigidbody Custom Editor
8+
#region MoverScriptNoRigidbody Custom Editor
99
#if UNITY_EDITOR
1010
using Unity.Netcode.Editor;
1111
using UnityEditor;
@@ -144,8 +144,7 @@ protected override void OnNetworkPreSpawn(ref NetworkManager networkManager)
144144

145145
/// <summary>
146146
/// We are using post spawn to handle any final spawn initializations.
147-
/// At this point we know all NetworkBehaviours on this instance has
148-
/// been spawned.
147+
/// At this point we know all NetworkBehaviours on this instance have been spawned.
149148
/// </summary>
150149
protected override void OnNetworkPostSpawn()
151150
{
@@ -182,14 +181,13 @@ protected override void OnNetworkPostSpawn()
182181

183182
public override void OnNetworkDespawn()
184183
{
185-
// Notify any client or server specific componant that this instance has despawned.
184+
// Notify any client or server specific component that this instance has despawned.
186185
NotifySpawnStatusChanged?.Invoke(false);
187186
if (IsLocalPlayer)
188187
{
189188
m_CharacterController.enabled = false;
190189
Camera.main.transform.SetParent(null, false);
191-
Camera.main.transform.position = m_CameraOriginalPosition;
192-
Camera.main.transform.rotation = m_CameraOriginalRotation;
190+
Camera.main.transform.SetPositionAndRotation(m_CameraOriginalPosition, m_CameraOriginalRotation);
193191
}
194192
base.OnNetworkDespawn();
195193
}

Examples/OverridingScenesAndPrefabs/Assets/Scripts/NetworkManagerBootstrapper.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -415,8 +415,7 @@ private void SetCameraDefaults()
415415
if (Camera.main != null && Camera.main.transform.parent != null)
416416
{
417417
Camera.main.transform.SetParent(null, false);
418-
Camera.main.transform.position = m_CameraOriginalPosition;
419-
Camera.main.transform.rotation = m_CameraOriginalRotation;
418+
Camera.main.transform.SetPositionAndRotation(m_CameraOriginalPosition, m_CameraOriginalRotation);
420419
}
421420
}
422421

@@ -522,7 +521,7 @@ private void StartDedicatedServer()
522521

523522
/// <summary>
524523
/// Register callbacks when the OnServerStarted callback is invoked.
525-
/// This makes it easier to know you are registering for events only
524+
/// This makes it easier to know you are registering for events only
526525
/// when the server successfully has started.
527526
/// </summary>
528527
private void ServerStarted()
@@ -578,11 +577,11 @@ private void HandleEditorKeyCommands()
578577
#else
579578
private void HandleConsoleKeyCommands()
580579
{
581-
if (Console.KeyAvailable)
580+
if (Console.KeyAvailable)
582581
{
583582
var networkManager = NetworkManager.Singleton;
584583
var keyPressed = Console.ReadKey(true);
585-
switch(keyPressed.Key)
584+
switch(keyPressed.Key)
586585
{
587586
case ConsoleKey.X:
588587
{

Examples/OverridingScenesAndPrefabs/Assets/Scripts/NetworkPrefabOverrideHandler.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaterni
4545
var gameObject = m_NetworkManager.IsClient ? Instantiate(NetworkPrefabOverride) : Instantiate(NetworkPrefab);
4646
// You could integrate spawn locations here and on the server side apply the spawn position at
4747
// this stage of the spawn process.
48-
gameObject.transform.position = position;
49-
gameObject.transform.rotation = rotation;
48+
gameObject.transform.SetPositionAndRotation(position, rotation);
5049
return gameObject.GetComponent<NetworkObject>();
5150
}
5251

@@ -64,4 +63,3 @@ public void Destroy(NetworkObject networkObject)
6463
Destroy(networkObject.gameObject);
6564
}
6665
}
67-

com.unity.netcode.gameobjects/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
2525

2626
### Fixed
2727

28+
- Made a variety of small performance improvements. (#3683)
2829

2930
### Security
3031

com.unity.netcode.gameobjects/Documentation~/basics/object-spawning.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,7 @@ This type of dynamically spawned `NetworkObject` typically is a simple wrapper c
153153
m_prefabInstance = Instantiate(prefabToSpawn);
154154

155155
// Optional, this example applies the spawner's position and rotation to the new instance
156-
m_prefabInstance.transform.position = transform.position;
157-
m_prefabInstance.transform.rotation = transform.rotation;
156+
m_prefabInstance.transform.SetPositionAndRotation(transform.position, transform.rotation);
158157

159158
// Get the instance's NetworkObject and Spawn
160159
m_SpawnedNetworkObject = m_prefabInstance.GetComponent<NetworkObject>();
@@ -233,8 +232,7 @@ public class SinglePooledDynamicSpawner : NetworkBehaviour, INetworkprefabInstan
233232
public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
234233
{
235234
m_prefabInstance.SetActive(true);
236-
m_prefabInstance.transform.position = transform.position;
237-
m_prefabInstance.transform.rotation = transform.rotation;
235+
m_prefabInstance.transform.position.SetPositionAndRotation(transform.position, transform.rotation);
238236
return m_SpawnedNetworkObject;
239237
}
240238

com.unity.netcode.gameobjects/Editor/CodeGen/NetworkBehaviourILPP.cs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1431,11 +1431,7 @@ private void ProcessNetworkBehaviour(TypeDefinition typeDefinition, string[] ass
14311431
MethodReference callMethod = rpcHandler;
14321432
if (typeDefinition.HasGenericParameters)
14331433
{
1434-
var genericTypes = new List<TypeReference>();
1435-
foreach (var parameter in typeDefinition.GenericParameters)
1436-
{
1437-
genericTypes.Add(parameter);
1438-
}
1434+
var genericTypes = new List<TypeReference>(typeDefinition.GenericParameters);
14391435
callMethod = callMethod.MakeGeneric(genericTypes.ToArray());
14401436
}
14411437

@@ -3101,11 +3097,7 @@ private MethodDefinition GenerateStaticHandler(MethodDefinition methodDefinition
31013097
var callMethod = (MethodReference)methodDefinition;
31023098
if (castType.HasGenericParameters)
31033099
{
3104-
var genericTypes = new List<TypeReference>();
3105-
foreach (var parameter in castType.GenericParameters)
3106-
{
3107-
genericTypes.Add(parameter);
3108-
}
3100+
var genericTypes = new List<TypeReference>(castType.GenericParameters);
31093101
castType = castType.MakeGenericInstanceType(genericTypes.ToArray());
31103102
callMethod = callMethod.MakeGeneric(genericTypes.ToArray());
31113103
}

com.unity.netcode.gameobjects/Editor/Configuration/NetcodeForGameObjectsProjectSettings.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public class NetcodeForGameObjectsProjectSettings : ScriptableSingleton<NetcodeF
2222

2323
private void OnEnable()
2424
{
25-
if (NetworkPrefabsPath == "")
25+
if (NetworkPrefabsPath.Length == 0)
2626
{
2727
NetworkPrefabsPath = DefaultNetworkPrefabsPath;
2828
}

com.unity.netcode.gameobjects/Editor/Configuration/NetcodeSettingsProvider.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ private static void OnDeactivate()
3636
if (settings.TempNetworkPrefabsPath != settings.NetworkPrefabsPath)
3737
{
3838
var newPath = settings.TempNetworkPrefabsPath;
39-
if (newPath == "")
39+
if (newPath.Length == 0)
4040
{
4141
newPath = NetcodeForGameObjectsProjectSettings.DefaultNetworkPrefabsPath;
4242
settings.TempNetworkPrefabsPath = newPath;

com.unity.netcode.gameobjects/Editor/HiddenScriptEditor.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ public class UnityTransportEditor : HiddenScriptEditor
5555

5656
private SerializedProperty m_ServerAddressProperty;
5757
private SerializedProperty m_ServerPortProperty;
58-
private SerializedProperty m_OverrideBindIpProperty;
5958

6059
private const string k_LoopbackIpv4 = "127.0.0.1";
6160
private const string k_LoopbackIpv6 = "::1";
@@ -76,7 +75,6 @@ private void Initialize()
7675

7776
m_ServerAddressProperty = connectionDataProperty.FindPropertyRelative(nameof(UnityTransport.ConnectionAddressData.Address));
7877
m_ServerPortProperty = connectionDataProperty.FindPropertyRelative(nameof(UnityTransport.ConnectionAddressData.Port));
79-
m_OverrideBindIpProperty = connectionDataProperty.FindPropertyRelative(nameof(UnityTransport.ConnectionAddressData.ServerListenAddress));
8078
}
8179

8280
/// <summary>
@@ -129,7 +127,7 @@ public override void OnInspectorGUI()
129127
overrideIp = EditorGUILayout.TextField("Override Bind IP (optional)", overrideIp);
130128
if (allowRemoteConnections)
131129
{
132-
if (overrideIp == "")
130+
if (overrideIp.Length == 0)
133131
{
134132
if (isIpV6)
135133
{

0 commit comments

Comments
 (0)