Muhammad Imran Tariq
Muhammad Imran Tariq

Reputation: 23352

Java performance avoid creating new in loop

I have a code like this

Map<String, List> searchMap = new HashMap<String, List>();
for(int i=0; i<something.size(); i++){
 List<String> list = new ArrayList<String>();
 list = getResult(...);
 ...
 searchMap.put(differentkey, list);
}

Each time I am creating new List in loop. How to avoid creating new list in loop.

Upvotes: 1

Views: 375

Answers (5)

user unknown
user unknown

Reputation: 36269

for(int i=0; i<something.size(); i++){
 List<String> list = new ArrayList<String>();
 list = getResult(...);

is equivalent to

for(int i=0; i<something.size(); i++){
 List<String> list = getResult(...);

But I'm not sure, whether you're really searching for this.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

Try this instead:

Map<String, List> searchMap = new HashMap<String, List>();
for(int i=0; i<something.size(); i++){
    List<String> list = getResult(...);
    ...
    searchMap.put(differentkey, list);
}

There's no need to construct a new list.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503779

Why would you want to? It looks like you want as many lists as you have keys, given that your map is from a key to a list... so you want that many distinct lists.

In particular, you don't want to just clear the list on each iteration - as otherwise each map entry will refer to the same list.

Now you don't have to create an empty list which you then ignore - you can assign the value of getResult() immediately to the variable, in the declaration:

List<String> list = getResult(...);

That's likely to still be creating a new list on each iteration (unless getResult() returns an existing one) but that's probably what you want anyway.

Note that there's no benefit in declaring the list variable outside the loop - the variable declaration doesn't affect performance, but it's generally a good idea to limit a variable's scope as much as possible - so I'd keep the declaration where it is.

Upvotes: 1

shift66
shift66

Reputation: 11958

Map<String, List> searchMap = new HashMap<String, List>();
List<String> list = new ArrayList<String>();
for(int i=0; i<something.size(); i++){
    list = getResult(...);
    ...
    searchMap.put(differentkey, list);
}

On the 4th line (list = getResult(...);) you're assigning a new object to your listvariable. So there's no need to create new list before that. Your variable will be replaced anyway.

Upvotes: 0

x4u
x4u

Reputation: 14085

Simply don't create the List at all since it is not even used in the code you have shown.

List<String> list = getResult(...);

Upvotes: 6

Related Questions