简体   繁体   中英

What is the most efficient way to concatenate strings in Dart?

Languages like Java, let you concatenate Strings using '+" operator.

But as strings are immutable, they advise one to use StringBuilder for efficiency if one is going to repeatedly concatenate a string.

What is the most efficient way to concatenate Strings in Dart?

https://api.dart.dev/stable/2.9.1/dart-core/StringBuffer-class.html

StringBuffer can be used for concatenating strings efficiently.

Allows for the incremental building of a string using write*() methods. The strings are concatenated to a single string only when toString is called.

It appears that if one uses StringBuffer, one is postponing the performance hit till toString is called?

There are a number of ways to concatenate strings:

  • String.operator + : string1 + string2 . This is the most straightforward. However, if you need to concatenate a lot of strings, using + repeatedly will create a lot of temporary objects, which is inefficient. (Also note that unlike other concatenation methods, + will throw an exception if either argument is null .)

  • String interpolation: '$string1$string2' . If you need to concatenate a fixed number of strings that are known in advance (such that you can use a single interpolating string), I would expect this to be reasonably efficient. If you need to incrementally build a string, however, this would have the same inefficiency as + .

  • StringBuffer . This is efficient if you need to concatenate a lot of strings.

  • Iterable.join : [string1, string2].join() . This internally uses a StringBuffer so would be equivalent.

If you need to concatenate a small, fixed number of strings, I would use string interpolation. It's usually more readable than using + , especially if there are string literals involved. Using StringBuffer in such cases would add some unnecessary overhead.

Here is what I understood:

It appears that performance will vary depending on your use case. If you use StringBuffer, and intend to concatenate a very large string, then as the concatenation occurs only when you call toString, it is at that point where you get the "performance hit".

But if you use "+", then each time you call "+" there is a performance hit. As strings are immutable, each time you concatenate two strings you are creating a new object which needs to be garbage collected.

Hence the answer seems to be to test for your situation, and determine which option makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM