Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing ArrayList with a new operator in Java?

Tags:

java

arraylist

What is the best practice for initializing an ArrayList in Java?

If I initialize a ArrayList using the new operator then the ArrayList will by default have memory allocated for 10 buckets. Which is a performance hit.

I don't know, maybe I am wrong, but it seems to me that I should create a ArrayList by mentioning the size, if I am sure about the size!

like image 251
Pradeep Avatar asked Dec 08 '22 01:12

Pradeep


1 Answers

Which is a performance hit.

I wouldn't worry about the "performance hit". Object creation in Java is very fast. The performance difference is unlikely to be measurable by you.

By all means use a size if you know it. If you don't, there's nothing to be done about it anyway.

The kind of thinking that you're doing here is called "premature optimization". Donald Knuth says it's the root of all evil.

A better approach is to make your code work before you make it fast. Optimize with data in hand that tells you where your code is slow. Don't guess - you're likely to be wrong. You'll find that you rarely know where the bottlenecks are.

like image 50
duffymo Avatar answered Dec 26 '22 04:12

duffymo