Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

split vs substring  RSS feed

 
fahad siddiqui
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which would give me a better performance advantage?
for substring, i would be first checking the indexOf and then subtringing in 2 parts.

The string would break to a max of 2 parts.
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37230
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither is likely to be time consuming enough to be a bottleneck. Go with the one that is clearer and easier to maintain - in this case split().
 
rajesh bala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
split() internally creates Pattern.compile which is an expensive operation. so I would say, use split() in an efficient way. Or use Pattern.compile(regex).split(this, limit); directly.

~Rajesh.B
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm with Jeanne here - simply use split() until it is proven to be a bottleneck for you application.
 
rajesh bala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FYI...

This is the snippet from String.java.

public String[] split(String regex, int limit) {
return Pattern.compile(regex).split(this, limit);
}

If you already know what you are trying to split, its always better to compile the regex and compile the pattern only once.

~Rajesh.B
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!