0

I need to maintain last 4 recent ids (It may not be in sequence). So I have added below code.

    long timeStamp = System.currentTimeMillis();
    Queue<Integer> autoIds = new LinkedList<Integer>(Arrays.asList(-1,-1,-1,-1));

    for(int i =1;i<2147483647;i++){
        autoIds.add(i);
        autoIds.poll();
    }
    System.out.println(System.currentTimeMillis()-timeStamp); 
    // 25436 or 26771... little different numbers but more then 24500
    System.out.println(recentUnregisteredModuleIds);

Later I thought removing size check in if condition, may increase performance so I removed and initialize queue with some dummy 4 values.

    long timeStamp = System.currentTimeMillis();
    Queue<Integer> autoIds = new LinkedList<Integer>();

    for(int i =1;i<2147483647;i++){
        autoIds.add(i);
        if(autoIds.size()>4){
            autoIds.poll();
        }
    }
    System.out.println(System.currentTimeMillis()-timeStamp); 
    // 19949 or 20425 ... less then 21000 in different times
    System.out.println(recentUnregisteredModuleIds);

But when I compare the execution time adding additional if condition to check queue size before poll is better in performance. I thought adding one additional condition will decrease the performance, here that's not true how ?

R D
  • 1,330
  • 13
  • 30
  • 1
    You probably want to read [*How do I write a correct micro-benchmark in Java?*](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java), but I'm confused by your question: How is "25436 or 26771... little different numbers but more then 24500" "better in performance" than "19949 or 20425 ... less then 21000 in different times"? Isn't 24500 greater than 21000, and thus, *worse* performance? As one would expect given the condition check? – T.J. Crowder Mar 13 '18 at 11:28
  • As of your edit the numbers match the "better in performance" description, but I have to say, I suspect observational error here given they were originally backward. Or just benchmarking vagaries. – T.J. Crowder Mar 13 '18 at 11:31
  • @T.J.Crowder 25436 or 26771.. and 19949 or 20425 ...are result for that code block – R D Mar 13 '18 at 11:31
  • Right. And when I posted my comment, you had the the numbers in the code blocks backward. – T.J. Crowder Mar 13 '18 at 11:32
  • Yes by mistake I have copied my result wrongly now corrected. Any idea why performance is better even-thought added one condition check ? – R D Mar 13 '18 at 11:35
  • I don't think it is. The way you're benchmarking is not rigorous enough to draw any conclusions from, see the linked question for details. (And when I run locally, I don't see much difference in times between the two.) If you do a rigorous benchmark, I suspect you'll find that there's not much in it either way, but that the version with the `if` isn't generally faster than the version without. – T.J. Crowder Mar 13 '18 at 11:39

0 Answers0