Hi
I am just wondering if i need dynamically create a html table, which way will be more efficient?
A. Use stringbuilder. For example, sb.append("<table border=0>""), for(i=0;i<10;i++){sb.append("<tr><td>abc</td></tr>")}, sb.append("</table>")
B. Use table control, t = new table, for(i=0;i<10;i++){tr=new tablerow, td=new tablecell, td.text="abc",tr.cells.add(td),t.rows.add(tr))
Thanks
~Mike
Hi
Honestly, i dont see it makes huge different
But I think B will quicker than A. because all table, row, cell are object. I think use object to create table will be faster than string built up.
Use the following code to test this:
private void RunTest(int count){ Stopwatch watch =new Stopwatch(); watch.Start();for (int i2 = 0; i2 < count; i2++) { Table table =new Table();for (int i = 0; i < 10; i++) { TableRow tr =new TableRow(); TableCell td =new TableCell(); td.Text ="abc"; tr.Cells.Add(td); table.Rows.Add(tr); } } watch.Stop(); Debug.WriteLine(watch.ElapsedMilliseconds); watch.Reset(); watch.Start();for (int i2 = 0; i2 < count; i2++) { StringBuilder sb =new StringBuilder(); sb.Append("<table border=0>");for (int i = 0; i < 10; i++) { sb.Append("<tr><td>abc</td></tr>"); } sb.Append("</table>"); } watch.Stop(); Debug.WriteLine(watch.ElapsedMilliseconds);}
I did the test with a count of 1500 which should show a difference and let it run 4 times. The outputs are as follows:
22 // Table
4 // StringBuilder
29
5
22
4
26
4
But, as you won't to that 1,500 times, there won't be a lot of difference concerning the performance.
Hi all,
I think the best way is using Table, TableRow and TableCell objects. You can create a table with all cells and rows you want and navigate throw them using their structure. However, if you want to create a simple table that has only two cells or something similar, it's quicker to use StringBuilder object or a string variable.
If the table doesn't need to be a server control, then I think it would be a little more efficient to use a StringBuilder. I?haven't?done?any?tests,?but?writing?out raw?HTML?generally incurs?less?overhead?than?instantiang?controls?for?everything. Any performance difference between the two approaches is going to be negligable though, so personally i'd go for whatever you find the more readable.
A third, and possible better approach would be to put your information into a DataTable and bind it to a GridView, DataList or Repeater.
I'd say A is going to be slightly more efficient but as already pointed out it'll be negligible. I personally like the markup in my code to be neat when viewed so B would probably better achieve that, even if its only for me debugging its output when it goes skewey.
0 comments:
Post a Comment