I have considered using this shortcut in my competition programming. I define a function:
private static int[] range(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = i;
}
return ret;
}
so that I can write my for loops slightly quicker, and slightly neater looking (when scanning code):
for (int i: range(n)) { doit(i); }
instead of:
for (int i = 0; i < n; i++) { doit(i); }
Are there any significant performance issues with this approach and what are they?
The code has a time limit to calculate a solution, but using the right algorithm it's usually possible to do this in a fraction of the time limit. The range function runs in O(n) and because we are going to run a O(n) loop anyway, there is no increase in time complexity. What about garbage collection? Anything else I'm not thinking of?
I will determine if I actually like using this method later, and if it's worth the overhead of typing out the functions at the start of the competition. Please don't answer about the style. (Competition coding produces some of the worst looking code you've ever seen, but it's all about getting it done on time and never looking at it again.)
To clarify, actual coding time is crucial in this competition and we can't bring pre-typed code. This generally means no code snippets either. The foreach
will make for loops quicker to type, and less error prone, in the rushed and messy coding environment. It is an alternative to macros in C++.
n
is large enough to cause issues with space allocation... I don't see any downsides. I actually ended up implementing similar functionality for my own purposes but with an iterator instead of an array. The array method should be faster at least for smalln
.for
over an array into your editor. Some clever IDEs will even list the arrays for you to choose from and add .length for you.