gpt4 book ai didi

dart - 在Dart中连接字符串的最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-03 04:40:06 24 4
gpt4 key购买 nike

像Java这样的语言,可以让您使用'+'运算符来连接字符串。
但是由于字符串是不可变的,因此如果要重复连接字符串,建议使用StringBuilder来提高效率。
在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.
看来,如果使用StringBuffer,则将性能降低推迟到调用toString之前?

最佳答案

有多种方法来串联字符串:

  • String.operator +:string1 + string2。这是最直接的。但是,如果需要连接许多字符串,则重复使用+将创建许多临时对象,这是低效的。 (还请注意,与其他串联方法不同,如果其中一个参数为+null将引发异常。)
  • 字符串插值:'$string1$string2'。如果您需要连接一定数量的事先已知的字符串(这样您就可以使用单个插值字符串),我希望这样做是相当有效的。但是,如果您需要增量构建字符串,则其效率与+相同。
  • StringBuffer。如果您需要连接很多字符串,这将非常有效。
  • Iterable.join :[string1, string2].join()。这在内部使用StringBuffer,因此是等效的。

  • 如果需要连接少量固定数目的字符串,则可以使用字符串插值。与使用 +相比,它通常更具可读性,尤其是在涉及字符串文字的情况下。在这种情况下使用 StringBuffer会增加一些不必要的开销。

    关于dart - 在Dart中连接字符串的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63388179/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com