C
Chris Uppal
NOBODY said:(I cannot believe the % of coders forgetting that 'new' is expensive...)
The question is: /how/ expensive ?
Go on, take a guess. How many milliseconds ? Or is it measured in
microseconds ? Or even nanoseconds ? Take a guess, before you read on...
Here's some test code:
====================
public class Main
implements Runnable
{
private final int m_steps;
public static void
main(String[] args)
{
new Thread(new Main(100)).run();
}
Main(int steps)
{
m_steps = steps;
}
public void
run()
{
for (;
{
tick();
tock();
}
}
void
tick()
{
int steps = m_steps * 1000000;
int[] array = new int[0];
int totalSize = 0;
long start = System.currentTimeMillis();
for (int i = 0; i < steps; i++)
{
totalSize += array.length;
array = new int[0];
}
long end = System.currentTimeMillis();
double secs = (end - start) / 1000.0;
System.out.print(m_steps + "M arrays allocated in " + secs + " seconds");
System.out.println(", total size: " + totalSize);
}
void
tock()
{
int steps = m_steps * 1000000;
int[] array = new int[0];
int totalSize = 0;
long start = System.currentTimeMillis();
for (int i = 0; i < steps; i++)
totalSize += array.length;
long end = System.currentTimeMillis();
double secs = (end - start) / 1000.0;
System.out.print("zero arrays allocated in " + secs + " seconds");
System.out.println(", total size: " + totalSize);
}
}
====================
On my machine, a 1.5Gz laptop, it sits in a steady loop allocating 0-length
arrays at a rate of around 40M per second (about 25 nanoseconds a go). The
reported times scale with both 'm_steps' and the size of the allocated arrays
so I don't think the allocations are being optimised away. (I did try
with -server too, and that's marginally quicker as you'd expect, and that
/does/ optimise the empty comparison loop (tock()) out completely, but not the
allocations afaict.)
There are contexts where allocation is slower than that -- not everyone is
running code on desktop class or more machines. Also there are contexts where
25 nanosecs is a long time -- though I doubt if many people reading this are
working in such a context. So, while I don't entirely disagree with you that
"'new' is expensive", I think that a better way to express it (for general
purposes) is that 'new' is /cheap/.
-- chris