views:

139

answers:

1

Hi!

What is best practice and, most importantly, the method that performs best?

I have a repeater where I want to manipulate the html depending on the value of the datasource. But as far as I know there are several ways to do this:

Method #1:


HTML:

<asp:Repeater ID="rptLinks" runat="server">
    <ItemTemplate>
     <li<%#GetLiClass(Container.DataItem("lnk_external")) %>>
      <a href="<%# Container.DataItem("lnk_url") %>" target="_blank"><%#Container.DataItem("lnk_name")%></a>
     </li>
    </ItemTemplate>
</asp:Repeater>

Backend:

Public Function GetLiClass(ByVal bExternal As Boolean) As String
 If bExternal Then
  Return " class=""externalLink"""
 Else
  Return ""
 End If
End Function


Method #2:


HTML:

<asp:Repeater ID="rptLinks" runat="server">
    <ItemTemplate>
     <li runat="server" id="liListElement">
      <a href="<%# Container.DataItem("lnk_url") %>" target="_blank"><%#Container.DataItem("lnk_name")%></a>
     </li>
    </ItemTemplate>
</asp:Repeater>

Backend:

Protected Sub rptLinks_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptLinks.ItemDataBound

 If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then

  If e.Item.DataItem("lnkExternal") Then
   Dim liListElement As HtmlGenericControl = e.Item.FindControl("liListElement")
   liListElement.Attributes.Add("class", "externalLink")
  End If

 End If

End Sub

So.. Which gives the best performance?

Method #1: Using an inline call to a function that writes out what I want.

Or Method #2 Using Repeater.ItemDataBound to manipulate the elements as I want.

Thanks in advance :)

+2  A: 

I prefer the first method and that's what I generally use. However, I use it because I think the code is more readable/understandable than the second method, not because I think it has better performance.

As it happens, I suspect that method #1 probably does have better (theoretical) performance than method #2, but I doubt if this difference could be reliably measured in any real-world tests.

You really shouldn't worry about it. Choose the code that you feel is the most readable/understandable. Any performance bottlenecks in your app won't be anything to do with this choice.

LukeH