Insert into room using list vs for loop In Android

Viewed 391

What is best for memory and performance ! I have some data came from fire base through a listener, should i put them on a list of object using for loop then insert the list to the room or make a for loop and looping the (insert to room) !!!

Method 1 :

List<object> list = new List<>. 
();
For (int i;i>= list.size; i++){
list.add(data);
}
InsertToRoom(list);

Method 2:

For (int i;i>= list.size; i++){
InsertToRoom(name, age)
}
1 Answers

I would recommend you to use only Method 1.
Because inside "Method 1" you are calling the expensive databse operation InsertToRoom() only once.

Whereas, inside "Method 2" you are calling the expensive database operations multiple times, i.e. the InsertToRoom() operation will be called multiple times until the for loop gets completed. This is not performant and efficient.

As a Good Android Citizen you should restrict multiple calls to database, unless genuinely required.

Hence, please go with Method 1.

Related