经典的过时言论——使用StringUtils.split替代普通split方法提升性能

本文通过实验对比了不同JDK版本下使用String.split方法与第三方库的性能差异,并解析了JDK1.8中String.split方法的优化原理。

经常能听到这个说法,甚至编程规范也会约束不让用String的split方法,那么是不是真的就很慢呢?测试代码如下

    public static void main(String[] args)
    {
        String str = "abc:abc:drdf:dfw:da";
        System.out.println(System.currentTimeMillis());
        for (int i = 0; i < 10000000; i++)
        {
            String[] strArr1 = str.split(":");
        }
        System.out.println(System.currentTimeMillis());
        for (int i = 0; i < 10000000; i++)
        {
            String[] strArr2 = StringUtils.split(str, ':');

        }
        System.out.println(System.currentTimeMillis());
    }

运行环境win7 jdk1.8,分别耗时2746ms和2312ms,可以看出来是差不多的,那么jdk1.6上呢?分别耗时6375ms和1478ms,4倍多的差距,应该就是这个说法的源泉了。

那么jdk1.8到底做了什么让耗时变小的呢?从String.split()的注释可以看到

fastpath if the regex is a
         (1)one-char String and this character is not one of the
            RegEx's meta characters ".$|()[{^?*+\\", or
         (2)two-char String and the first char is the backslash and
            the second is not the ascii digit or ascii letter.
就是对我们常用的这种字符串分隔(包括非正则表达式字符的单个字符和反斜杠转移的双字符),做了提前处理,然后再进行正则表达式的匹配,所以速度快了不少。有感于江南白衣jvm调优的一份ppt,技术在不断的进步,很多以前的说法稍不注意就会过时,如同最早的null放在等号前、加号拼接字符串会变慢,都逐步的不是问题了,前人的总结指不定就过时了。


package com.app.controller; import com.alibaba.fastjson.JSON; import com.annotation.IgnoreAuth; import com.baidu.aip.face.AipFace; import com.baidu.aip.face.MatchRequest; import com.baidu.aip.util.Base64Util; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.entity.ConfigEntity; import com.service.CommonService; import com.service.ConfigService; import com.utils.BaiduUtil; import com.utils.FileUtil; import com.utils.R; import com.utils.StringUtil; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; /** * 通用接口 */ @RestController public class CommonController{ private static final Logger logger = LoggerFactory.getLogger(CommonController.class); @Autowired private CommonService commonService; @Autowired private ConfigService configService; private static AipFace client = null; private static String BAIDU_DITU_AK = null; @RequestMapping("/location") public R location(String lng,String lat) { if(BAIDU_DITU_AK==null) { BAIDU_DITU_AK = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "baidu_ditu_ak")).getValue(); if(BAIDU_DITU_AK==null) { return R.error("请在配置管理中正确配置baidu_ditu_ak"); } } Map<String, String> map = BaiduUtil.getCityByLonLat(BAIDU_DITU_AK, lng, lat); return R.ok().put("data", map); } /** * 人脸比对 * * @param face1 人脸1 * @param face2 人脸2 * @return */ @RequestMapping("/matchFace") public R matchFace(String face1, String face2, HttpServletRequest request) { if(client==null) { /*String AppID = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "AppID")).getValue();*/ String APIKey = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "APIKey")).getValue(); String SecretKey = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "SecretKey")).getValue(); String token = BaiduUtil.getAuth(APIKey, SecretKey); if(token==null) { return R.error("请在配置管理中正确配置APIKey和SecretKey"); } client = new AipFace(null, APIKey, SecretKey); client.setConnectionTimeoutInMillis(2000); client.setSocketTimeoutInMillis(60000); } JSONObject res = null; try { File file1 = new File(request.getSession().getServletContext().getRealPath("/upload")+"/"+face1); File file2 = new File(request.getSession().getServletContext().getRealPath("/upload")+"/"+face2); String img1 = Base64Util.encode(FileUtil.FileToByte(file1)); String img2 = Base64Util.encode(FileUtil.FileToByte(file2)); MatchRequest req1 = new MatchRequest(img1, "BASE64"); MatchRequest req2 = new MatchRequest(img2, "BASE64"); ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>(); requests.add(req1); requests.add(req2); res = client.match(requests); System.out.println(res.get("result")); } catch (FileNotFoundException e) { e.printStackTrace(); return R.error("文件不存在"); } catch (IOException e) { e.printStackTrace(); } return R.ok().put("data", com.alibaba.fastjson.JSONObject.parse(res.get("result").toString())); } /** * 获取table表中的column列表(联动接口) * @return */ @RequestMapping("/option/{tableName}/{columnName}") @IgnoreAuth public R getOption(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName,String level,String parent) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", tableName); params.put("column", columnName); if(StringUtils.isNotBlank(level)) { params.put("level", level); } if(StringUtils.isNotBlank(parent)) { params.put("parent", parent); } List<String> data = commonService.getOption(params); return R.ok().put("data", data); } /** * 根据table中的column获取单条记录 * @return */ @RequestMapping("/follow/{tableName}/{columnName}") @IgnoreAuth public R getFollowByOption(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName, @RequestParam String columnValue) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", tableName); params.put("column", columnName); params.put("columnValue", columnValue); Map<String, Object> result = commonService.getFollowByOption(params); return R.ok().put("data", result); } /** * 修改table表的sfsh状态 * @param map * @return */ @RequestMapping("/sh/{tableName}") public R sh(@PathVariable("tableName") String tableName, @RequestBody Map<String, Object> map) { map.put("table", tableName); commonService.sh(map); return R.ok(); } /** * 获取需要提醒的记录数 * @param tableName * @param columnName * @param type 1:数字 2:日期 * @param map * @return */ @RequestMapping("/remind/{tableName}/{columnName}/{type}") @IgnoreAuth public R remindCount(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName, @PathVariable("type") String type,@RequestParam Map<String, Object> map) { map.put("table", tableName); map.put("column", columnName); map.put("type", type); if(type.equals("2")) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); Date remindStartDate = null; Date remindEndDate = null; if(map.get("remindstart")!=null) { Integer remindStart = Integer.parseInt(map.get("remindstart").toString()); c.setTime(new Date()); c.add(Calendar.DAY_OF_MONTH,remindStart); remindStartDate = c.getTime(); map.put("remindstart", sdf.format(remindStartDate)); } if(map.get("remindend")!=null) { Integer remindEnd = Integer.parseInt(map.get("remindend").toString()); c.setTime(new Date()); c.add(Calendar.DAY_OF_MONTH,remindEnd); remindEndDate = c.getTime(); map.put("remindend", sdf.format(remindEndDate)); } } int count = commonService.remindCount(map); return R.ok().put("count", count); } /** * 圖表统计 */ @IgnoreAuth @RequestMapping("/group/{tableName}") public R group1(@PathVariable("tableName") String tableName, @RequestParam Map<String,Object> params) { params.put("table1", tableName); List<Map<String, Object>> result = commonService.chartBoth(params); return R.ok().put("data", result); } /** * 单列求和 */ @RequestMapping("/cal/{tableName}/{columnName}") @IgnoreAuth public R cal(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", tableName); params.put("column", columnName); Map<String, Object> result = commonService.selectCal(params); return R.ok().put("data", result); } /** * 分组统计 */ @RequestMapping("/group/{tableName}/{columnName}") @IgnoreAuth public R group(@PathVariable("tableName") String tableName, @PathVariable("columnName") String columnName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", tableName); params.put("column", columnName); List<Map<String, Object>> result = commonService.selectGroup(params); return R.ok().put("data", result); } /** * (按值统计) */ @RequestMapping("/value/{tableName}/{xColumnName}/{yColumnName}") @IgnoreAuth public R value(@PathVariable("tableName") String tableName, @PathVariable("yColumnName") String yColumnName, @PathVariable("xColumnName") String xColumnName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", tableName); params.put("xColumn", xColumnName); params.put("yColumn", yColumnName); List<Map<String, Object>> result = commonService.selectValue(params); return R.ok().put("data", result); } /** * 下面为新加的 * * * */ /** * 查询字典表的分组求和 * tableName 表名 * groupColumn 分组字段 * sumCloum 统计字段 * @return */ @RequestMapping("/newSelectGroupSum") public R newSelectGroupSum(@RequestParam Map<String,Object> params) { logger.debug("newSelectGroupSum:,,Controller:{},,params:{}",this.getClass().getName(),params); List<Map<String, Object>> result = commonService.newSelectGroupSum(params); return R.ok().put("data", result); } /** tableName 查询表 condition1 条件1 condition1Value 条件1值 average 计算平均评分 取值 有值 Number(res.data.value.toFixed(1)) 无值 if(res.data){} * */ @IgnoreAuth @RequestMapping("/queryScore") public R queryScore(@RequestParam Map<String, Object> params) { logger.debug("queryScore:,,Controller:{},,params:{}",this.getClass().getName(),params); Map<String, Object> queryScore = commonService.queryScore(params); return R.ok().put("data", queryScore); } /** * 查询字典表的分组统计总条数 * tableName 表名 * groupColumn 分组字段 * @return */ @RequestMapping("/newSelectGroupCount") public R newSelectGroupCount(@RequestParam Map<String,Object> params) { logger.debug("newSelectGroupCount:,,Controller:{},,params:{}",this.getClass().getName(),params); List<Map<String, Object>> result = commonService.newSelectGroupCount(params); return R.ok().put("data", result); } /** * 当前表的日期分组求和 * tableName 表名 * groupColumn 分组字段 * sumCloum 统计字段 * dateFormatType 日期格式化类型 1:年 2:月 3:日 * @return */ @RequestMapping("/newSelectDateGroupSum") public R newSelectDateGroupSum(@RequestParam Map<String,Object> params) { logger.debug("newSelectDateGroupSum:,,Controller:{},,params:{}",this.getClass().getName(),params); String dateFormatType = String.valueOf(params.get("dateFormatType")); if("1".equals(dateFormatType)){ params.put("dateFormat", "%Y"); }else if("2".equals(dateFormatType)){ params.put("dateFormat", "%Y-%m"); }else if("3".equals(dateFormatType)){ params.put("dateFormat", "%Y-%m-%d"); }else{ R.error("日期格式化不正确"); } List<Map<String, Object>> result = commonService.newSelectDateGroupSum(params); return R.ok().put("data", result); } /** * * 查询字典表的分组统计总条数 * tableName 表名 * groupColumn 分组字段 * dateFormatType 日期格式化类型 1:年 2:月 3:日 * @return */ @RequestMapping("/newSelectDateGroupCount") public R newSelectDateGroupCount(@RequestParam Map<String,Object> params) { logger.debug("newSelectDateGroupCount:,,Controller:{},,params:{}",this.getClass().getName(),params); String dateFormatType = String.valueOf(params.get("dateFormatType")); if("1".equals(dateFormatType)){ params.put("dateFormat", "%Y"); }else if("2".equals(dateFormatType)){ params.put("dateFormat", "%Y-%m"); }else if("3".equals(dateFormatType)){ params.put("dateFormat", "%Y-%m-%d"); }else{ R.error("日期格式化类型不正确"); } List<Map<String, Object>> result = commonService.newSelectDateGroupCount(params); return R.ok().put("data", result); } /** * 饼状图 * -- 饼状图 查询当前表 -- 查询字典表【月】 -- 统计 -- 查询某个月的每个类型的订单销售数量 -- 求和 -- 查询某个月的每个类型的订单销售额 -- 查询某个字符串【月】 -- 统计 -- 查询某个月的每个员工的订单销售数量 -- 求和 -- 查询某个月的每个员工的订单销售额 -- 查询时间【年】 -- 统计 -- 查询每个月的订单销售数量 -- 求和 -- 查询每个月的订单销售额 -- 饼状图 查询级联表 -- 查询字典表 -- 统计 -- 查询某个月的每个类型的订单销售数量 -- 求和 -- 查询某个月的每个类型的订单销售额 -- 查询某个字符串 -- 统计 -- 查询某个月的每个员工的订单销售数量 -- 求和 -- 查询某个月的每个员工的订单销售额 -- 查询时间 -- 统计 -- 统计每个月的订单销售数量 -- 求和 -- 查询每个月的订单销售额 */ /** * 柱状图 -- 柱状图 查询当前表 -- 某个【年,月】 -- 当前表 2 级联表 1 -- 统计 -- 【日期,字符串,下拉框】 -- 求和 -- 【日期,字符串,下拉框】 -- 柱状图 查询级联表 -- 某个【年,月】 -- 统计 -- 【日期,字符串,下拉框】 -- 求和 -- 【日期,字符串,下拉框】 */ /** * 柱状图求和 */ @RequestMapping("/barSum") public R barSum(@RequestParam Map<String,Object> params) { logger.debug("barSum方法:,,Controller:{},,params:{}",this.getClass().getName(), com.alibaba.fastjson.JSONObject.toJSONString(params)); Boolean isJoinTableFlag = false;//是否有级联表相关 String one = "";//第一优先 String two = "";//第二优先 //处理thisTable和joinTable 处理内容是把json字符串转为Map并把带有,的切割为数组 //当前表 Map<String,Object> thisTable = JSON.parseObject(String.valueOf(params.get("thisTable")),Map.class); params.put("thisTable",thisTable); //级联表 String joinTableString = String.valueOf(params.get("joinTable")); if(StringUtil.isNotEmpty(joinTableString)) { Map<String, Object> joinTable = JSON.parseObject(joinTableString, Map.class); params.put("joinTable", joinTable); isJoinTableFlag = true; } if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("date")))){//当前表日期 thisTable.put("date",String.valueOf(thisTable.get("date")).split(",")); one = "thisDate0"; } if(isJoinTableFlag){//级联表日期 Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable"); if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("date")))){ joinTable.put("date",String.valueOf(joinTable.get("date")).split(",")); if(StringUtil.isEmpty(one)){ one ="joinDate0"; }else{ if(StringUtil.isEmpty(two)){ two ="joinDate0"; } } } } if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("string")))){//当前表字符串 thisTable.put("string",String.valueOf(thisTable.get("string")).split(",")); if(StringUtil.isEmpty(one)){ one ="thisString0"; }else{ if(StringUtil.isEmpty(two)){ two ="thisString0"; } } } if(isJoinTableFlag){//级联表字符串 Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable"); if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("string")))){ joinTable.put("string",String.valueOf(joinTable.get("string")).split(",")); if(StringUtil.isEmpty(one)){ one ="joinString0"; }else{ if(StringUtil.isEmpty(two)){ two ="joinString0"; } } } } if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("types")))){//当前表类型 thisTable.put("types",String.valueOf(thisTable.get("types")).split(",")); if(StringUtil.isEmpty(one)){ one ="thisTypes0"; }else{ if(StringUtil.isEmpty(two)){ two ="thisTypes0"; } } } if(isJoinTableFlag){//级联表类型 Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable"); if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("types")))){ joinTable.put("types",String.valueOf(joinTable.get("types")).split(",")); if(StringUtil.isEmpty(one)){ one ="joinTypes0"; }else{ if(StringUtil.isEmpty(two)){ two ="joinTypes0"; } } } } List<Map<String, Object>> result = commonService.barSum(params); List<String> xAxis = new ArrayList<>();//报表x轴 List<List<String>> yAxis = new ArrayList<>();//y轴 List<String> legend = new ArrayList<>();//标题 if(StringUtil.isEmpty(two)){//不包含第二列 List<String> yAxis0 = new ArrayList<>(); yAxis.add(yAxis0); legend.add("数值"); for(Map<String, Object> map :result){ String oneValue = String.valueOf(map.get(one)); String value = String.valueOf(map.get("value")); xAxis.add(oneValue); yAxis0.add(value); } }else{//包含第二列 Map<String, HashMap<String, String>> dataMap = new LinkedHashMap<>(); if(StringUtil.isNotEmpty(two)){ for(Map<String, Object> map :result){ String oneValue = String.valueOf(map.get(one)); String twoValue = String.valueOf(map.get(two)); String value = String.valueOf(map.get("value")); if(!legend.contains(twoValue)){ legend.add(twoValue);//添加完成后 就是最全的第二列的类型 } if(dataMap.containsKey(oneValue)){ dataMap.get(oneValue).put(twoValue,value); }else{ HashMap<String, String> oneData = new HashMap<>(); oneData.put(twoValue,value); dataMap.put(oneValue,oneData); } } } for(int i =0; i<legend.size(); i++){ yAxis.add(new ArrayList<String>()); } Set<String> keys = dataMap.keySet(); for(String key:keys){ xAxis.add(key); HashMap<String, String> map = dataMap.get(key); for(int i =0; i<legend.size(); i++){ List<String> data = yAxis.get(i); if(StringUtil.isNotEmpty(map.get(legend.get(i)))){ data.add(map.get(legend.get(i))); }else{ data.add("0"); } } } System.out.println(); } Map<String, Object> resultMap = new HashMap<>(); resultMap.put("xAxis",xAxis); resultMap.put("yAxis",yAxis); resultMap.put("legend",legend); return R.ok().put("data", resultMap); } /** * 柱状图统计 */ @RequestMapping("/barCount") public R barCount(@RequestParam Map<String,Object> params) { logger.debug("barCount方法:,,Controller:{},,params:{}",this.getClass().getName(), com.alibaba.fastjson.JSONObject.toJSONString(params)); Boolean isJoinTableFlag = false;//是否有级联表相关 String one = "";//第一优先 String two = "";//第二优先 //处理thisTable和joinTable 处理内容是把json字符串转为Map并把带有,的切割为数组 //当前表 Map<String,Object> thisTable = JSON.parseObject(String.valueOf(params.get("thisTable")),Map.class); params.put("thisTable",thisTable); //级联表 String joinTableString = String.valueOf(params.get("joinTable")); if(StringUtil.isNotEmpty(joinTableString)) { Map<String, Object> joinTable = JSON.parseObject(joinTableString, Map.class); params.put("joinTable", joinTable); isJoinTableFlag = true; } if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("date")))){//当前表日期 thisTable.put("date",String.valueOf(thisTable.get("date")).split(",")); one = "thisDate0"; } if(isJoinTableFlag){//级联表日期 Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable"); if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("date")))){ joinTable.put("date",String.valueOf(joinTable.get("date")).split(",")); if(StringUtil.isEmpty(one)){ one ="joinDate0"; }else{ if(StringUtil.isEmpty(two)){ two ="joinDate0"; } } } } if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("string")))){//当前表字符串 thisTable.put("string",String.valueOf(thisTable.get("string")).split(",")); if(StringUtil.isEmpty(one)){ one ="thisString0"; }else{ if(StringUtil.isEmpty(two)){ two ="thisString0"; } } } if(isJoinTableFlag){//级联表字符串 Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable"); if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("string")))){ joinTable.put("string",String.valueOf(joinTable.get("string")).split(",")); if(StringUtil.isEmpty(one)){ one ="joinString0"; }else{ if(StringUtil.isEmpty(two)){ two ="joinString0"; } } } } if(StringUtil.isNotEmpty(String.valueOf(thisTable.get("types")))){//当前表类型 thisTable.put("types",String.valueOf(thisTable.get("types")).split(",")); if(StringUtil.isEmpty(one)){ one ="thisTypes0"; }else{ if(StringUtil.isEmpty(two)){ two ="thisTypes0"; } } } if(isJoinTableFlag){//级联表类型 Map<String, Object> joinTable = (Map<String, Object>) params.get("joinTable"); if(StringUtil.isNotEmpty(String.valueOf(joinTable.get("types")))){ joinTable.put("types",String.valueOf(joinTable.get("types")).split(",")); if(StringUtil.isEmpty(one)){ one ="joinTypes0"; }else{ if(StringUtil.isEmpty(two)){ two ="joinTypes0"; } } } } List<Map<String, Object>> result = commonService.barCount(params); List<String> xAxis = new ArrayList<>();//报表x轴 List<List<String>> yAxis = new ArrayList<>();//y轴 List<String> legend = new ArrayList<>();//标题 if(StringUtil.isEmpty(two)){//不包含第二列 List<String> yAxis0 = new ArrayList<>(); yAxis.add(yAxis0); legend.add("数值"); for(Map<String, Object> map :result){ String oneValue = String.valueOf(map.get(one)); String value = String.valueOf(map.get("value")); xAxis.add(oneValue); yAxis0.add(value); } }else{//包含第二列 Map<String, HashMap<String, String>> dataMap = new LinkedHashMap<>(); if(StringUtil.isNotEmpty(two)){ for(Map<String, Object> map :result){ String oneValue = String.valueOf(map.get(one)); String twoValue = String.valueOf(map.get(two)); String value = String.valueOf(map.get("value")); if(!legend.contains(twoValue)){ legend.add(twoValue);//添加完成后 就是最全的第二列的类型 } if(dataMap.containsKey(oneValue)){ dataMap.get(oneValue).put(twoValue,value); }else{ HashMap<String, String> oneData = new HashMap<>(); oneData.put(twoValue,value); dataMap.put(oneValue,oneData); } } } for(int i =0; i<legend.size(); i++){ yAxis.add(new ArrayList<String>()); } Set<String> keys = dataMap.keySet(); for(String key:keys){ xAxis.add(key); HashMap<String, String> map = dataMap.get(key); for(int i =0; i<legend.size(); i++){ List<String> data = yAxis.get(i); if(StringUtil.isNotEmpty(map.get(legend.get(i)))){ data.add(map.get(legend.get(i))); }else{ data.add("0"); } } } System.out.println(); } Map<String, Object> resultMap = new HashMap<>(); resultMap.put("xAxis",xAxis); resultMap.put("yAxis",yAxis); resultMap.put("legend",legend); return R.ok().put("data", resultMap); } } 我现在使用springboot3.5.3和java17,这些文件需要修改吗,怎么修改,修改后的文件需要重新给出注释并给出完整的代码
07-12
<think>首先,用户的问题是:“我想查找StringUtils.split使用方法 请问StringUtils.split使用方法”。用户明确要求了解StringUtils.split使用方法。 参考提供的引用: - 引用[1]:讨论了String.splitStringUtils.split的对比,提到StringUtils.split来自commons-lang3。 - 引用[2]:指出StringUtils.split有两个包:org.springframework.util.StringUtils 和 org.apache.commons.lang3.StringUtils。 - 引用[3]:展示了使用StringUtils.split的一个示例,强调它与String.split不同。 - 引用[4]:讨论了StringUtils.split在处理多个分割字符时的行为。 - 引用[5]:对比了String.splitStringUtils.split性能。 关键点: - StringUtils.split需要从Apache Commons Lang或Spring Framework引入。 - 它有特定的语法和行为,不同于Java的String.split。 系统指令: - 使用中文回答。 - 结构清晰,逐步解决问题。 - 所有数学表达式用$...$格式(但这个问题不涉及数学,所以可能不适用)。 - 独立公式用$$...$$格式单独成段(也不适用)。 - 末尾自然地添加引用标识,如[^1]。 - 生成相关问题。 回答结构: 1. **介绍StringUtils.split**:解释它是什么,并提到常见的包。 2. **基本用法**:展示如何使用StringUtils.split。 3. **参数解释**:解释其参数,如分隔符。 4. **行为示例**:基于引用[3]和[4],展示一些具体行为。 5. **注意事项**:强调与String.split的区别。 6. **性能考虑**:简要提及性能对比(引用[5])。 7. **引用标识**:在相关信息后添加引用。 8. **生成相关问题**:在最后添加相关问题。 确保回答真实可靠:基于提供的引用。用户提到的引用是站内引用,所以我可以直接引用它们。 中文回答:整个回答用中文。 生成相关问题:在最后添加几个相关问题,格式类似于示例中的“§§相关问题§§”。 详细内容: - StringUtils.split通常用于字符串分割。 - 它有两种常见版本:Apache Commons Lang 和 Spring Framework版本。用户可能指的是Apache的,因为他们提到了commons-lang3(引用[1])。 - 基本语法:`String[] StringUtils.split(String str, String separator)` - 示例:如引用[3]中的例子:`StringUtils.split("aabbccdd", "bc")` 输出什么? - 引用[3]显示:对于`"aabbccdd"`分割为`"bc"`,输出是`["aa", "dd"]`,因为它将每个字符视为分隔符。 - 与String.split的区别:String.split使用正则表达式,而StringUtils.split可能更简单处理字符分割。 - 引用[4]提到:处理多个分割字符时,它不支持字符串作为分隔符;它把每个字符独立处理。 - 性能:引用[5]说StringUtils.split性能可能不如String.split,因为它使用循环而非索引跳跃。 回答大纲: 1. **开头**:概述StringUtils.split是什么。 2. **导入依赖**:如何引入它。 3. **基本使用方法**:代码示例。 4. **行为说明**:基于引用讨论特定行为。 5. **对比String.split**:简要比较。 6. **常见问题**:如何避免坑。 7. **结束**:总结。 8. **相关问题**:添加相关问题。 相关问题想法: 1. 如何在项目中使用Apache Commons Lang库? 2. StringUtils.split与其他字符串分割方法的区别是什么? 3. 如何处理复杂的字符串分割场景? 4. 为什么使用StringUtils.split而不是String.split? 5. StringUtils.split在处理多字符分隔符时有什么限制? 确保引用标识自然添加:例如,在提到对比时加[^1],在行为示例时加[^3],在性能时加[^5]。 </think>### StringUtils.split 使用方法指南 StringUtils.split 是 Java 中用于字符串分割的工具方法,主要来自 Apache Commons Lang 或 Spring Framework 库。它与 Java 内置的 `String.split()` 不同,避免了正则表达式的复杂性,但在使用时需注意特定行为。以下基于您提供的引用信息,逐步解释其使用方法、语法和注意事项,确保回答真实可靠。 --- ### 1. **基本介绍与依赖导入** StringUtils.split 是一个静态方法,用于将字符串按指定分隔符拆分为数组。常见于两个库: - **Apache Commons Lang3**:`org.apache.commons.lang3.StringUtils.split(String str, String separator)` - **Spring Framework**:`org.springframework.util.StringUtils.split(String str, String separator)` 您需要先在项目中导入相关依赖: - Apache Commons Lang3 (Maven): ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> <!-- 使用最新版本 --> </dependency> ``` - Spring Framework (Maven): ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.22</version> <!-- 使用最新版本 --> </dependency> ``` 推荐使用 Apache 版本,因其更通用且文档齐全[^1][^2]。 --- ### 2. **核心语法与参数说明** 方法签名: ```java String[] StringUtils.split(String str, String separator) ``` - **str**: 待分割的字符串(可为 `null`,此时返回 `null`)。 - **separator**: 分隔符字符串(可为 `null`,此时默认按空白字符分割)。 - **返回值**: 分割后的字符串数组(如果输入 `null` 或空字符串,返回空数组)。 **关键行为**: - 分隔符 `separator` 被视为 **字符集合**,而非整体字符串。例如,`"bc"` 表示按字符 `'b'` 或 `'c'` 分割,而非子串 `"bc"`[^3][^4]。 - 分割时忽略多余空白(如连续分隔符被视为单个分隔点)。 - 性能方面:相比 `String.split()`,它不使用正则校验,但通过循环迭代处理,可能导致在大数据量时性能略低[^5]。 --- ### 3. **使用示例与代码演示** 以下基于 Apache Commons Lang3 的示例(确保已导入 `import org.apache.commons.lang3.StringUtils;`): #### **示例 1:基本分割** ```java String str = "apple,banana,orange"; String[] result = StringUtils.split(str, ","); // 按逗号分割 // 输出: ["apple", "banana", "orange"] ``` #### **示例 2:分隔符为字符集合(常见坑点)** 如引用[^3]所示: ```java String str = "aabbccdd"; String[] result = StringUtils.split(str, "bc"); // 按 'b' 或 'c' 分割 // 输出: ["aa", "dd"] 而非 ["aa","","dd"] 或 ["aa","dd"] ``` 原因:分隔符 `"bc"` 被解释为字符集,即 `'b'` 或 `'c'` 都触发分割。连续的分隔符(如 `"bb"` 或 `"cc"`)被视为一个分割点,中间不保留空字符串[^3][^4]。 #### **示例 3:处理 null 或空白** ```java String[] result1 = StringUtils.split(null, ","); // 返回 null String[] result2 = StringUtils.split("", ","); // 返回空数组 [] String[] result3 = StringUtils.split(" a b c ", " "); // 按空格分割,忽略多余空白 // 输出: ["a", "b", "c"] ``` --- ### 4. **与 String.split() 的关键区别** - **String.split()**: 使用正则表达式(如 `str.split(",")`),适合复杂分割,但性能开销大,且需处理空字符串(如 `"a,,b".split(",")` 返回 `["a", "", "b"]`)[^1][^5]。 - **StringUtils.split()**: - 优点:简化字符级分割,自动处理空白。 - 缺点:不支持多字符作为整体分隔符(如无法按子串 `"bc"` 分割),且对大字符串性能可能略低[^4][^5]。 示例对比: ```java // String.split() 使用正则 "aabbccdd".split("bc"); // 报错:无效正则(需转义) "aabbccdd".split("b|c"); // 正确:输出 ["aa","","","dd"] // StringUtils.split() 简单分割 StringUtils.split("aabbccdd", "bc"); // 输出 ["aa","dd"] ``` --- ### 5. **常见问题与最佳实践** - **避坑指南**: - 如果需要按子串分割(如 `"bc"` 整体),改用 `String.split()` 或自定义逻辑(如 `StringUtils.splitByWholeSeparator()`)。 - 避免在性能敏感场景使用:对于超长字符串,测试表明 `String.split()` 在简单分隔符下可能更快[^5]。 - **何时使用**:适合快速分割字符集(如 CSV 文件解析)、处理空白字符或避免正则复杂性。 - **替代方法**:Apache Commons Lang 提供 `splitByWholeSeparator()` 支持整体字符串分隔符[^4]。 --- ### 总结 StringUtils.split 简化了字符串分割,尤其适合按字符集分割的场景,但需注意分隔符是字符集合而非整体字符串。推荐优先使用 Apache Commons Lang3 版本,并结合实际需求选择工具方法。更多细节参考 [Apache Commons Lang 文档](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html)[^1][^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值