Re: Bulk Array Element Allocation, is it faster?
On 9/24/2011 9:17 PM, Jan Burse wrote:
Dear All,
I just wonder wether modern JIT do optimize
Code of the following form:
Bla[] bla = new Bla[n];
for (int i=0; i<n; i++) {
bla[i] = new Bla();
}
When I use the above in my code, my application
spends 8800 ms in the benchmark I have.
When I then change the code to:
Bla[] bla = new Bla[n];
...
if (bla[i]==null)
bla[i] = new Bla();
..
So instead of allocating all elements at once,
I will allocate them on demand in the subsequent
flow of my application.
This could be a win if you will actually use only a few of
the array elements, and if constructing a Bla is expensive (for
example, if it involves I/O). If Bla's are cheap to make, or if
you'll wind up using most of them anyhow, there's no obvious
reason to conditionalize.
When I use the above in my code, my application
now suddently sends 9600 ms in the benchmark
I have.
Nine percent longer. But I'm highly suspicious of those nice,
round numbers: It seems an unlikely coincidence that two rather
different chunks of code should both execute in even tenths of
seconds. Are you sure you've measured what you want to measure?
Are you sure that what you want to measure is the important thing?
So I wonder whether eventually the JIT has
a way to detect the bulk allocate of the first
version and transform it into something more
efficient than my lazy allocation.
Based on your (suspect) timings, "just leave it be" would be
exactly the kind of improvement you ask for. The JIT very likely
does something like that already :-)
--
Eric Sosman
esosman@ieee-dot-org.invalid