迭代DataSnapshot的子节点的有效方法

时间:2016-10-12 14:51:41

标签: android firebase garbage-collection firebase-realtime-database

这两个代码片段中的哪一个更有效,或者两者都相同?

假设数据库是这样的:

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){
      //..
    }

});

0 个答案:

没有答案