String.substring vs String []。split [英] String.substring vs String[].split

查看:116
本文介绍了String.substring vs String []。split的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个逗号分隔的字符串,当调用 String.split(,)时,它返回的数组大小约为60.在特定的用例中,我只需要获取将从数组返回的第二个值的值。因此,例如Q,BAC,233,sdf,sdf,我想要的是第一个'后的字符串值,'和第二个','之前。我对性能的问题是我最好使用substring自己解析它还是使用split方法,然后获取数组中的第二个值?任何输入将不胜感激。这种方法每秒会被调用数百次,所以重要的是我理解关于性能和内存分配的最佳方法。

-Duncan

解决方案

由于字符串.Split 返回一个 string [] ,使用60-way Split 会导致每行约60个不必要的分配。 Split 遍历整个字符串,并创建60个新对象加上数组对象本身。在这六十一个对象中,你只保留一个,让垃圾收集器处理剩下的六十个。



如果你在一个紧密的循环中调用它,一个子串肯定是效率更高:它会遍历字符串的一部分直到第二个逗号,然后创建一个新对象。

  String s =quick,brown,fox,jumps,over,the,lazy,dog; 
int from = s.indexOf(',');
int to = s.indexOf(',',from + 1);
String brown = s.substring(from + 1,to);

以上打印 棕色



当您多次执行此操作时,子字符串在时间上顺利胜出:1,000,000次迭代 split 取3.36s,而1,000,000次迭代 substring 只需要0.05s。而这只有八个组件在字符串中!六十个组件的差异将更加激烈。

I have a comma delaminated string that when calling String.split(",") it returns an array size of about 60. In a specific use case I only need to get the value of the second value that would be returned from the array. So for example "Q,BAC,233,sdf,sdf," all I want is the value of the string after the first ',' and before the second ','. The question I have for performance am I better off parsing it myself using substring or using the split method and then get the second value in the array? Any input would be appreciated. This method will get called hundreds of times a second so it's important I understand the best approach regarding performance and memory allocation.

-Duncan

解决方案

Since String.Split returns a string[], using a 60-way Split would result in about sixty needless allocations per line. Split goes through your entire string, and creates sixty new object plus the array object itself. Of these sixty one objects you keep exactly one, and let garbage collector deal with the remaining sixty.

If you are calling this in a tight loop, a substring would definitely be more efficient: it goes through the portion of your string up to the second comma ,, and then creates one new object that you keep.

String s = "quick,brown,fox,jumps,over,the,lazy,dog";
int from = s.indexOf(',');
int to = s.indexOf(',', from+1);
String brown = s.substring(from+1, to);

The above prints brown

When you run this multiple times, the substring wins on time hands down: 1,000,000 iterations of split take 3.36s, while 1,000,000 iterations of substring take only 0.05s. And that's with only eight components in the string! The difference for sixty components would be even more drastic.

这篇关于String.substring vs String []。split的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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