Home >Java >javaTutorial >Performance comparison of Java function comparison

Performance comparison of Java function comparison

WBOY
WBOYOriginal
2024-04-20 13:03:01912browse

Performance comparison of different Java comparison functions: equals() takes the longest time. compareTo() and compare() have similar performance and are both better than equals().

Performance comparison of Java function comparison

Performance comparison of Java function comparison

In Java development, it is necessary to optimize the performance of the code. Comparison functions are one of the common operations in code, and choosing an appropriate comparison function is crucial to improving efficiency. This article will compare different Java comparison functions and provide practical examples to illustrate their performance differences.

Comparison functions

Java provides a variety of comparison functions, including:

  • equals(): comparison Whether two objects are equal.
  • compareTo(): Compare the size order of two objects.
  • compare(): Returns the integer result of comparing two objects.

Performance comparison

In order to compare the performance of these functions, we created the following code snippet:

List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
    numbers.add(i);
}

// 使用 equals() 比较
long startTime = System.currentTimeMillis();
for (int i = 0; i < numbers.size() - 1; i++) {
    numbers.get(i).equals(numbers.get(i + 1));
}
long endTime = System.currentTimeMillis();
System.out.println("equals() 比较耗时:" + (endTime - startTime) + "ms");

// 使用 compareTo() 比较
startTime = System.currentTimeMillis();
for (int i = 0; i < numbers.size() - 1; i++) {
    numbers.get(i).compareTo(numbers.get(i + 1));
}
endTime = System.currentTimeMillis();
System.out.println("compareTo() 比较耗时:" + (endTime - startTime) + "ms");

// 使用 compare() 比较
startTime = System.currentTimeMillis();
for (int i = 0; i < numbers.size() - 1; i++) {
    Integer.compare(numbers.get(i), numbers.get(i + 1));
}
endTime = System.currentTimeMillis();
System.out.println("compare() 比较耗时:" + (endTime - startTime) + "ms");

Practical case

The above code snippet compares equals(), compareTo() and compare() on a list of 1 million integers Function. The running results are as follows:

equals() 比较耗时:13111ms
compareTo() 比较耗时:1093ms
compare() 比较耗时:1112ms

It can be seen from these results that the performance of compareTo() and compare() is significantly better than equals() Compare.

The above is the detailed content of Performance comparison of Java function comparison. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn