You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2022/02/14 11:55:47 UTC

[GitHub] [kafka] ruanwenjun commented on a change in pull request #11754: MINOR: Optimize collection method in Utils

ruanwenjun commented on a change in pull request #11754:
URL: https://github.com/apache/kafka/pull/11754#discussion_r805769215



##########
File path: clients/src/main/java/org/apache/kafka/common/utils/Utils.java
##########
@@ -764,10 +764,7 @@ public static ByteBuffer ensureCapacity(ByteBuffer existingBuffer, int newLength
      */
     @SafeVarargs
     public static <T> Set<T> mkSet(T... elems) {
-        Set<T> result = new HashSet<>((int) (elems.length / 0.75) + 1);
-        for (T elem : elems)
-            result.add(elem);
-        return result;
+        return new HashSet<>(Arrays.asList(elems));

Review comment:
       Yes, I got your concern. The `Arrays.asList(elems) ` just copy the reference of elems.
   And I create a benchmark test looks like below
   ```java
   @State(Scope.Benchmark)
   @Fork(value = 1)
   @Warmup(iterations = 3)
   @Measurement(iterations = 10)
   @BenchmarkMode(Mode.AverageTime)
   @OutputTimeUnit(TimeUnit.MILLISECONDS)
   public class CreateSetTest {
   
       private int[] inits = new int[100];
   
       @Setup(Level.Trial)
       public void setUp() {
           for (int i = 0; i < inits.length; i++) {
               inits[i] = ThreadLocalRandom.current().nextInt();
           }
       }
   
       @Benchmark
       public void testCreateHashSet1() {
           HashSet<int[]> ints = new HashSet<>(Arrays.asList(inits));
       }
   
       @Benchmark
       public void testCreateHashSet2() {
           Set<Integer> result = new HashSet<>((int) (inits.length / 0.75) + 1);
           for (Integer elem : inits)
               result.add(elem);
       }
   
   
       public static void main(String[] args) throws RunnerException {
           Options opt = new OptionsBuilder()
               .include(CreateSetTest.class.getSimpleName())
               .forks(2)
               .build();
   
           new Runner(opt).run();
       }
   }
   ```
   
   The test result 
   ```
   Benchmark                Mode  Cnt   Score    Error  Units
   CreateSetTest.testCreateHashSet1  avgt   20  ≈ 10⁻⁴           ms/op
   CreateSetTest.testCreateHashSet2  avgt   20   0.001 ±  0.001  ms/op
   ```
   
   It seems it will not cause performance reduce.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org