Java 拆分 String 性能 [英] Java split String performances

查看:19
本文介绍了Java 拆分 String 性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的应用程序中的当前代码:

Here is the current code in my application:

String[] ids = str.split("/");

在分析应用程序时,字符串拆分花费了不可忽略的时间.此外,split 方法采用正则表达式,这里是多余的.

When profiling the application, a non-negligeable time is spent string splitting. Also, the split method takes a regular expression, which is superfluous here.

我可以使用什么替代方法来优化字符串拆分?StringUtils.split 是否更快?

What alternative can I use in order to optimize the string splitting? Is StringUtils.split faster?

(我会尝试和测试自己,但分析我的应用程序需要很多时间.)

(I would've tried and tested myself but profiling my application takes a lot of time.)

推荐答案

String.split(String) 如果您的模式只有一个字符长,则不会创建正则表达式.当按单个字符拆分时,它将使用非常有效的专用代码.StringTokenizer 在这种特殊情况下并没有快多少.

String.split(String) won't create regexp if your pattern is only one character long. When splitting by single character, it will use specialized code which is pretty efficient. StringTokenizer is not much faster in this particular case.

这是在 OpenJDK7/OracleJDK7 中引入的.这是错误报告提交.我在这里做了一个简单的基准测试.

This was introduced in OpenJDK7/OracleJDK7. Here's a bug report and a commit. I've made a simple benchmark here.

$ java -version
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)

$ java Split
split_banthar: 1231
split_tskuzzy: 1464
split_tskuzzy2: 1742
string.split: 1291
StringTokenizer: 1517

这篇关于Java 拆分 String 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆