• Post Reply Bookmark Topic Watch Topic
  • New Topic

Choosing between direct String replace and String check-replace  RSS feed

 
Tapas Chand
Ranch Hand
Posts: 614
9
BSD Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers
I have a task where I need to replace certain String with another in a text file having 5000 odd lines on average. I have couple of approaches. Just need some expert opinion regarding performance.
Approach 1:

Approach 2:

Will it be a overhead in approach 1 calling replaceAll for each record
or will it be a overhead in approach 2 calling contains for each record.
 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we forget about performance for a minute, does it make sense to make the contains check before doing the replaceAll?
 
Tapas Chand
Ranch Hand
Posts: 614
9
BSD Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well I have already delivered using the 1st approach.
but I was little curious that in 1st approach 'replaceAll' is called for each record, but in 2nd it will be called for few but 'contains' will be called for each records.
Just in case if 'replaceAll' takes much more time than 'contains', then 2nd approach would have been better.
This was my curiosity.
 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the _ is at the start of the String then contains will return quicker and checking first may help but if _ is at the end then contains will run through the whole String unnecessarily. Checking first may therefore result in better or worse performance based on the content being checked. Where files are involved it's unlikely that optimizing performance time this way will have a significant impact on the overall process time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!