TLE in JAVA because of the way I iterated collection

I am trying to figure out why this solution is getting TLE and why this is getting accepted.

It’s not like ACed solution is passing just by a margin, but rather it’s taking half of the time than TLEd solution.

The difference in both solutions is only at line 125 where I have to output my final answer.
I used
In AC Solution : list.forEach( x -> pn(x)) // pn is just used for printing
This is java8 style of iterating over collection

TLE Solution : for (String x : list) pn(x);
This is trivial for each style loop.

I searched it on the internet for the performance difference among two styles of the loop but was not able to get satisfactory answers, many sources have mentioned both are equal in terms of performance.
Can somebody help me to understand this behavior?

1 Like

I don’t know about Java, but if you are sure both styles don’t have any significant time differences, then read the following: Link1 Link2 Link3 and especially this comment.

Hope that helps. :smiley:
Please update your post tags if you feel this needs to be seen from administration side.

1 Like

Think that second type copies x every time, when first just have link to it

2 Likes

thanks ,got something new to learn and can you tell me what is this void watch(Object…a) method does? in your template

The watch function displays the contents of a particular data-structure(Object as in java).
For instance, the data structure is an Array, as array is an Object, the function(or precisely ‘method’ as termed in java) takes variable arguments(represented by …) and then this object is processed according to its class.
Different data-structures have different class names, hence there is a lot of conditional statements.

1 Like

Where can I read more about this ? or any links to refer ?

Yes, @piyush33patel is right, i tried to write this function for quick debugging purpose, otherwise you have to write long println statements for some data structures like Arrays.toString(arr) for arrays etc.