开发者

In a loop what is better, using the same object or instantiating a new object on each iteration?

In the below shown examples, the former approach instant开发者_JAVA技巧iates an object of type SearchResult for each iteration whereas the latter one instantiates the object only once and uses it for all the iterations.

using (DbDataReader reader = (DbDataReader)dbObject.ExecuteReader(command))
        {
            if (reader.HasRows)
            {
                List<SearchResult> searchResults = new List<SearchResult>();
                while (reader.Read())
                {
                    SearchResult searchResult = new SearchResult();
                    searchResult.AppName = Convert.ToString(reader["AppName"]);
                    searchResults.Add(searchResult);
                }
            }
        }

OR

using (DbDataReader reader = (DbDataReader)dbObject.ExecuteReader(command))
        {
            if (reader.HasRows)
            {
                List<SearchResult> searchResults = new List<SearchResult>();
                SearchResult searchResult = new SearchResult();
                while (reader.Read())
                {                        
                    searchResult.AppName = Convert.ToString(reader["AppName"]);
                    searchResults.Add(searchResult);
                }
            }
        }

Which is the better approach to handle this?

Thanks and kindly ignore my naiveness. :)


The first approach is better as the 2nd one won't work as intended as you're using the same instance each time and over writing the property. You're going to end up with a List of SearchResult's with all the same value! So definitely the first version.

You need to use the first version or instantiate a new instance each time like this:

SearchResult searchResult;
while (reader.Read())
{
      searchResult = new SearchResult();
      searchResult.AppName = Convert.ToString(reader["AppName"]);
      searchResults.Add(searchResult);
}

EDIT This is of course assuming SearchResult is a class, if it is in fact a struct then it is a value type and this will not be a problem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜