Are these string operations equivalent in Java and Python?

Consider the following two code blocks: http://ideone.com/3nNdVs

String[] matches = new String[] {"Foo", "Bar"};
long start = System.nanoTime();
for(int i=0; i< 1000000; i++) {
    String name = "This String is Foo Bar";
    for (String s : matches){
        name = name.replace(s, "");
    }
}
System.out.println((System.nanoTime() - start)/1000000);

and http://ideone.com/v8wg6m

matches = {"Foo", "Bar"}
start = time.time()
for x in xrange(1000000):
    name = "This String is Foo Bar"
    for s in matches:
        name = name.replace(s, "")
print time.time() - start

When trying to compare the performance of the two, I found that one that is implemented in Java takes about 50% longer than Python. This came as a shock to me, as I expected the Python version to be slower.

So, the first question: are there better or faster ways to perform these two functions?

Secondly, if not, why is the Java version slower than Python?

+4
source share
2 answers

, python , .replace java regex, , .replace.

, , , - org.apache.commons.lang3.StringUtils.replaceEach, , , , , .

long start = System.nanoTime();
for(int i=0; i< 1000000; i++) {
    String name = "This String is Foo Bar";
    name = StringUtils.replaceEach(name, matches, replaces);
}
System.out.println((System.nanoTime() - start)/1000000);

, cany , apache commons.

1/4 , .replace 1/2 , python.

python,

+2

Python timeit:

import timeit

setup = """
matches = {'Foo', 'Bar'}
for x in xrange(1000000):
  name = 'This String is Foo Bar'
  for s in matches:
    name = name.replace(s, '')
"""

print min(timeit.Timer(setup=setup).repeat(10))
-1

Source: https://habr.com/ru/post/1532778/


All Articles