0

Working at object mapping with Java and JDBC for SQL Server I wondered myself if I would create a variable to save the value that returns a select sentence or if I could put the sentence in the foreach loop.

I have post the complete function but the question is only about the foreach loop. Both options works good for me, but I wanted to know if there is any difference about efficiency or if exists any case where the first one could fail.

public static List<User> UserList()
{
    BD miBD = new BD(BD_SERVER,BD_NAME);
    ArrayList<User> list = new ArrayList<User>(); 

    for(Object[] tuple: miBD.Select("SELECT name,password FROM tUser;"))
    {
        String id = (String)tuple[0];
        String p = (String)tuple[1];
        User u = new User(id,p);
        list.add(u);
    }

    return list;
}

or

    List<Object[]> tupleList = miBD.Select("SELECT name,password FROM tUser;") 
    for(Object[] tuple: tupleList)
    {
        String id = (String)tuple[0];
        String p = (String)tuple[1];
        User u = new User(id,p);
        list.add(u);
    }
    return lista;
}

Which is more advisable to use?

Kishore
  • 819
  • 9
  • 20
Shondeslitch
  • 1,049
  • 1
  • 13
  • 26

1 Answers1

0

In terms of performance they are exactly the same.

The first variant is one line shorter so go with that.

wero
  • 32,544
  • 3
  • 59
  • 84