Java String.replace () vs. String.replaceFirst () vs homebrew

I have a class that processes a lot of text. For each line whose length is between 100 and 2000 characters, I execute 30 different line notes.

Example:

string modified;
for(int i = 0; i < num_strings; i++){
 modified = runReplacements(strs[i]);
 //do stuff
}

public runReplacements(String str){
  str = str.replace("foo","bar");
  str = str.replace("baz","beef");
  ....
  return str;
}

'foo', 'baz' and all other "targets" should appear only once and are string literals (there is no need for a real regular expression).

As you can imagine, performance bothers me :)

Considering this,

  • replaceFirst()seems like a bad choice because he will not use it Pattern.LITERALand will do additional processing that is not required.

  • replace() seems like a bad choice because it will traverse the entire line looking for multiple instances that need to be replaced.

, , , , String.replaceFirst() String.replace() Pattern.compile . , , :

  • Pattern.compile() ( ) (.. p1 - p30)

  • pX: p1.matcher(str).replaceFirst(Matcher.quoteReplacement("desiredReplacement"));

, ( ), regex, .

, ?

+5
3

, ?

!; -)

ETA: snarky, . " ...", - , (, ), . , , , . , in vivo , . ( , ...)

+3

/. , :

  • - , / .

, , match/replace , , - . " ", ; , "bazoo", . , - Java; JVM.

. ? !

(, "(foo | baz)" ), Matcher.find(int), , HashMap StringBuilder . (, , , /... . .)

() , , , /.

+2

Does it not disappoint when you ask a question and get a bunch of tips telling you to do a lot of work and figure it out for yourself?

I am using replaceAll ();

(I have no idea if this is really the most effective, I just do not want you to feel that you have lost money on this issue and received nothing.)

[edit] PS. After that, you can measure it.

[edit 2] PPS. (and let us know what you found)

0
source

All Articles