![]() ![]() ![]() Only to be followed by “new improved” language constructs that go into a long discussion of Iterable vs Sequence vs range operations, to wind up with a lot more code and hidden implications that must be considered (instantiation of the full list being one, foreach being about 3x slower than explicit for loop is another). When I read threads like this I feel like I fell into a Bizzaro Universe where the simplicity of a C for loop with its explicitly exposed initialization, looping condition and next iteration stepping, without any hidden costs that you have to “keep in mind” beyond what you write, is considered undesirable. There could be additional motivation, but in general I think that classic for loop should be deprecated and replaced by functional-style operations wherever it is possible. In my example, you can simply replace i by AtomicInteger and make your operations thread safe. Pitfall number four occurs when you have some parallel operations messing with i. In my example you can do it easily by replacing if by when. You will have to either delegate step calculation to additional function which is even worse, or rewrite everything. You won’t be able to do it with for anymore. Pitfall number three: Suppose you want a more complicated behavior and need three different steps instead of two. You do it in one place, but forget to do in another and now you have two iterations with different number of steps. Pitfall number two: For some reason, you want to change the behavior of your dynamic step. You should obviously never do it, but changing the increment is the first step in this direction. Pitfall number one: You accidentally or intentionally changing i somewhere inside your loop. ![]() The problem arises when you have a large code. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |