fork download
  1. import java.util.Random;
  2. import java.util.Arrays;
  3.  
  4. public class Main {
  5. private static Random rng = new Random();
  6. private static String[] ourStrings = {
  7. "1.one", "2.two", "3.three"
  8. };
  9.  
  10. private static int[] doItWithEquals(String[] entries) {
  11. int[] results = new int[entries.length];
  12. for (int i = 0; i < entries.length; ++i) {
  13. results[i] = -1;
  14. for (int j = 0; j < ourStrings.length; ++j) {
  15. if (ourStrings[j].equals(entries[i])) {
  16. results[i] = j;
  17. break;
  18. }
  19. }
  20. }
  21. return results;
  22. }
  23.  
  24. private static int[] doItWithBinarySearch(String[] entries) {
  25. int[] results = new int[entries.length];
  26. for (int i = 0; i < entries.length; ++i) {
  27. results[i] = Arrays.binarySearch(ourStrings, entries[i]);
  28. }
  29. return results;
  30. }
  31.  
  32. private static int[] doItWithReferences(String[] entries) {
  33. int[] results = new int[entries.length];
  34. for (int i = 0; i < entries.length; ++i) {
  35. results[i] = -1;
  36. for (int j = 0; j < ourStrings.length; ++j) {
  37. if (ourStrings[j] == entries[i]) {
  38. results[i] = j;
  39. break;
  40. }
  41. }
  42. }
  43. return results;
  44. }
  45.  
  46. private static String[] generateList(int size) {
  47. String[] result = new String[size];
  48. for (int i = 0; i < size; ++i) {
  49. result[i] = ourStrings[rng.nextInt(ourStrings.length)];
  50. }
  51. return result;
  52. }
  53.  
  54. public static void main(String[] s) {
  55. long totalForReferences = 0;
  56. long totalForEquals = 0;
  57. long totalForSearch = 0;
  58. int iterationCount = 1000;
  59.  
  60. for (int i = 0; i < iterationCount; ++i) {
  61. String[] testData = generateList(10000);
  62.  
  63. long start = System.nanoTime();
  64. int[] resultsWithReferences = doItWithReferences(testData);
  65. totalForReferences += System.nanoTime() - start;
  66.  
  67. start = System.nanoTime();
  68. int[] resultsWithEquals = doItWithEquals(testData);
  69. totalForEquals += System.nanoTime() - start;
  70.  
  71. start = System.nanoTime();
  72. int[] resultsWithBinarySearch = doItWithBinarySearch(testData);
  73. totalForSearch += System.nanoTime() - start;
  74.  
  75. if (
  76. !Arrays.equals(resultsWithReferences, resultsWithEquals) ||
  77. !Arrays.equals(resultsWithReferences, resultsWithBinarySearch)
  78. ) {
  79. throw new AssertionError("Results don't match");
  80. }
  81. }
  82. long referencesTime = totalForReferences / iterationCount;
  83. long equalsTime = totalForEquals / iterationCount;
  84. long searchTime = totalForSearch / iterationCount;
  85.  
  86. System.out.printf(
  87. "References: %d ns\nEquals: %d ns\nBinary search: %d ns\n",
  88. referencesTime, equalsTime, searchTime
  89. );
  90. }
  91. }
Success #stdin #stdout 1.91s 380224KB
stdin
Standard input is empty
stdout
References: 167643 ns
Equals: 356585 ns
Binary search: 629974 ns