这两个代码片段中的哪一个更有效,或者两者都相同?
假设数据库是这样的:
root
- userUID
-- messageUID
---- text:""
---- sentTo:""
-- messageUID2 {...}
-- messageUID3 {...}
-- messageUID4 {...}
然后我尝试的第一件事就是这个
DatabaseReference ref = FirebaseDatabase.getInstance().child(userId).addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
//..
ArrayList<Message> messageList = new ArrayList<>();
for(DataSnapshot messageSnapshot: dataSnapshot.getChildren()){
Message message = messageSnapshot.getValue(Message.class);
messageList.add(message);
}
//..
}
@Override
public void onCancelled(DatabaseError databaseError){
//..
}
});
然后我注意到我会创建很多Message对象。这会更有效吗?
DatabaseReference ref = FirebaseDatabase.getInstance().child(userId).addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
//..
ArrayList<Message> messageList = new ArrayList<>();
Message message = new Message("","");
for(DataSnapshot messageSnapshot: dataSnapshot.getChildren()){
message.setText(messageSnapshot.getValue("text");
message.setSentTo(messageSnapshot.getValue("sentTo");
messageList.add(message);
}
//..
}
@Override
public void onCancelled(DatabaseError databaseError){
//..
}
});