Is AsList() better than ToList() with IDbConnection.Query() which returns IEnumerable?

后端 未结 2 453
遥遥无期
遥遥无期 2021-01-02 02:50

I read this answer from Marc Gravell (@MarcGravell): https://stackoverflow.com/a/47790712/5779732

The last line says:

As a minor optimization

2条回答
  •  旧巷少年郎
    2021-01-02 03:34

    AsList is a custom Dapper extension method. All it does is checks if IEnumerable you pass to it is really List. If it is - it returns it back, just casts to List. If it's not - it calls regular ToList. The point is - ToList() always creates a copy, even if what you pass to it is already a list. AsList() method avoids doing this copy, and so is useful if such copy is unnecessary.

    In this specific scenario, you have the following code:

    multipleresult.Read()
    

    where multipleresult is GridReader. Read has buffered argument which is true by default. When its true - Read will really return List, so by calling ToList you will copy that list again without much reason.

    The same is true for IDbConnection.Query() - is also has buffered parameter, which is true by default, so it will also by default return List.

    If you prefer to use ToList() - you can pass buffered: false to Query() or Read() to avoid creating that additional copy.

提交回复
热议问题