I have an array, for example (in Java)
int[] a = new int[N];
I have worked with it and now want to have array with zeros.
What will take less time: to create a new Array(it will be initialized will zeros) or iterate through existing one and fill it with zeros?
I suppose whatever answer is, it will be the same in C++ ?
Chances are that you’re better off filling an existing array than creating a new one. Memory allocation can be very expensive relatively speaking. Indeed, if your favorite language provides you new arrays that are guaranteed to be zeroed out, it is probably filling them for you under the covers.
That said, this type of choice is a micro-optimization. In most cases, it won’t make any discernible difference. And if you find yourself in a specific case where you think it might make an important difference, you’re much better asking a profiler than asking StackOverflow.
Edit I’ll add one more caveat: Particularly in garbage collected languages like Java, you’re better off reusing existing objects than creating new ones if the reuse can be done cleanly. As a general rule of thumb.
Reedit … Unless the object(s) in question are expected to be very short lived. Probably some additional caveats too. And so back to “ask the profiler.”