Android String.format() 引发的卡顿问题

String.format() 是 Java 中用于创建格式化字符串的方法,Android 作为基于 Java 的平台,同样提供了这个功能。这个方法允许我们构建一个带有占位符的字符串,然后将这些占位符替换为具体的值。

String.format() 方法的用法与 printf() 在 C 语言中的用法十分相似。我们可以指定字符串中的每一个占位符的格式,比如:整数、浮点数、字符串等,然后通过 String.format() 的参数传递实际的值来替换这些占位符。

一个简单的使用实例:

java 复制代码
String name = "张三";
int age = 25;
String formattedString = String.format("我的名字是 %s,我今年 %d 岁。", name, age);
System.out.println(formattedString);  // 我的名字是 张三,我今年 25 岁。

最近在检测应用的性能时,发现在短时间内大量调用 String.format() 时会引发卡顿,所以马上进入源码看看有没有哪里能够优化的


java 复制代码
    public static String format(String format, Object... args) {
        return new Formatter().format(format, args).toString();
    }

比较简单,String.format() 方法中 new 了一个 Formatter 然后调用里面的函数

java 复制代码
package java.util;

public final class Formatter implements Closeable, Flushable {
    private Appendable a;

    public Formatter() {
        this(Locale.getDefault(Locale.Category.FORMAT), new StringBuilder());
    }

    public Formatter(Appendable a) {
        this(Locale.getDefault(Locale.Category.FORMAT), nonNullAppendable(a));
    }

    private Formatter(Locale l, Appendable a) {
        this.a = a;
        // ...
    }
}

Formatter 类中的无参构造函数中是直接 new 了一个 StringBuilder,而这个 StringBuilder 承接了整个 format 流程的产物进行拼接,最后调用 toString 输出


在这里我们可以知道,在短时间内大量的调用 String.format() 方法,Formatter 和 StringBuilder 对象会不停得创建,那么优化方案就水落石出了(将 Formatter 和 StringBuilder 对象往外提)

Kotlin 复制代码
object FormatUtils {
    private val stringBuilder by lazy { StringBuilder() }
    private val formatter by lazy { Formatter(stringBuilder) }

    fun format(formatString: String, vararg value: String): String {
        stringBuilder.setLength(0)
        formatter.format(formatString, value)
        return stringBuilder.toString()
    }
}

需要注意的是,上述优化可能在处理少量的简单字符串时并不会明显提升性能。而对于大量或复杂的字符串操作,应用这些方法才能带来显著的性能提升。如何优化取决于具体的使用场景和性能需求。

相关推荐
低调小一1 天前
Android传统开发 vs Android Compose vs HarmonyOS ArkUI 对照表
android·华为·harmonyos
雨白1 天前
Java 多线程指南:从基础用法到线程安全
android·java
00后程序员张1 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
程序员江同学1 天前
ovCompose + AI 开发跨三端的 Now in Kotlin App
android·kotlin·harmonyos
2501_915106321 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
消失的旧时光-19431 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
灿烂阳光g1 天前
SELinux 策略文件编写
android·linux
.豆鲨包1 天前
【Android】Viewpager2实现无限轮播图
android·java
xiangxiongfly9151 天前
Android CoordinatorLayout+AppBarLayout+CollapsingToolbarLayout实现折叠置顶效果
android·折叠