Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize string and text in Unity

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to optimize strings and text in Unity. It is very detailed and has a certain reference value. Friends who are interested must read it!

String and text:

In Unity projects, dealing with strings and text often causes performance problems. In C #, strings are immutable. Any operation on a string will reassign the new string, which is very expensive. If string concatenation operations are performed repeatedly in multiple loops, it can cause performance problems, especially for long strings or large datasets.

Therefore, concatenating N strings allocates an intermediate string, so successive operations put pressure on heap memory.

When we need to manipulate strings in multiple loops or every frame, remember to use StringBuilder to manipulate strings. StringBuilder can also be reused to further reduce memory allocation.

For more information on the use of strings, please refer to the documentation released by Microsoft:

Best Practices for Using Strings in .NET docs.microsoft.com

Https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings

Geographical restrictions and sequence comparison:

A core problem with string-related code is the inadvertent use of the default, slow string API. These API are intended for commercial applications that can handle characters that appear in text about different cultures and grammatical rules.

For example, the following code returns true when running in some areas where American English is used. When running in Europe, return false.

Tip: Unity scripts are run based on American English.

For most projects, this is completely unnecessary. And we simply compare each character to determine whether the two strings are equal, which is about 10 times faster than using the above method. Of course, we can also call the String.Equals method and set the comparison type StringComparison.Ordinal to implement:

Inefficient built-in string API:

In addition to the order comparison mentioned above, there are also some C # strings that are relatively inefficient in API. For example: String.Format,String.StartsWith and String.EndsWith. Here are some test data given by Unity:

It can be seen that if we implement String.StartsWith and String.EndsWith ourselves, the execution efficiency will be much higher. For the implementation method, please refer to the following figure:

Regular expression:

Regular expressions are very performance-consuming in terms of string matching and string manipulation. Moreover, the C# class library also implements regular expressions. So even if you call a function as simple as IsMatch, you will temporarily allocate a lot of memory. In our development, apart from the temporary allocation of memory after initialization, we should not be allowed to temporarily allocate more memory elsewhere.

If you must use regular expressions, be careful not to use static Regex.Match and Regex.Replace methods. These two methods compile the regular expression dynamically, but do not cache the generated object.

Here is an example of using regular expressions:

Each time more than one code is executed, it generates 5kb memory garbage. To reduce garbage generation, we need to ReFactor the above code:

In this example, each call to myRegExp.Match produces only 320b of memory garbage. It still consumes a lot of memory for simple string matching, but it's a big improvement over previous examples.

Therefore, if regular expressions are immutable string constants, it would be more efficient to precompile them as the first argument to Regex's constructor. These Regex objects can also be reused.

XML, JSON and other long text parsing:

Parsing text is usually a time-consuming operation in loading. In some cases, it takes more time to parse the text than loading and instantiate Assets.

The reason for this depends on the text parser we use. The built-in XML parser in C # is very flexible, but it cannot optimize some special data layouts.

Many third-party parsers are built on reflection. Although using reflection in development is a good choice (because it adapts well to changes in the layout of data), using reflection is very slow.

Unity has introduced a local solution with built-in JSONUtility API (see https://docs.unity3d.com/ScriptReference/JsonUtility.html), which provides an interface to Unity's serialization system for processing JSON data. In many ways it is a better JSON parser than C #. But it also has its drawbacks. It cannot serialize many complex data types, such as dictionaries, without adding additional code. (during Unity serialization, see the ISerializationCallbackReceiver interface to facilitate the conversion of some complex data types)

If you encounter performance problems in text parsing, you can consider the following solutions:

1. Parsing during Build

When we need to parse the text, it's best to avoid doing this in the game. We can parse the text into binary files during Build. To speed up the reading.

two。 Data segmentation and delayed loading

The second situation is that we need to split the data that can be parsed into small pieces. Once segmented, the data can be parsed at different times. Ideally, we determine which part of the data will be used, and then load only that part of the data.

3. Thread

For data that does not need to be manipulated with Unity API, it can be parsed in another thread. This can improve the utilization of multicore CPU, which is very useful. Of course, we need to be careful to avoid deadlocks when writing code.

The above is all the content of the article "how to optimize strings and text in Unity". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report