[Edu-sig] How to Improve code performance

Seth David Schoen schoen@loyalty.org
Mon, 29 Oct 2001 22:11:12 -0800


Titu Kim writes:

> Hi,
> I am little obssessed with my own coded after i
> found out it is slow. I am trying to construct a html
> table string from a result that i obtain from
> database.My code segment look like this: assume result
>  holds 2D list.
>  *******  method********************************
>  def f1(item):
>      return "<td>"+str(item)+"</td>"
>  *****************************************
>  ************main program piece***********
>  tab = "<table align='center' border='1'>\n"
>  for x in result:
>     tab = tab + "<tr>"
>     tab = tab + string.join(map(f1,x),"")+"</tr>\n"
>  tab = tab + "</table>"
>  print "Content-type:text/html\n"
>  print tab
>  **********************************************
>  Can anyone improve this code segment? Thanks alot

If all you do with tab is print it out, you don't need to do all
of those string operations, or function calls:

print "Content-type: text/html"
print "<table align='center' border='1'>"
for x in result:
	print "<tr>"
	for item in x:
		print "<td>"+str(item)+"</td>"
	print "</tr>"
print "</table>"

Printing output right away would have lower overhead and use less
memory.  If you know something about the data type of "item", you
could also use the % operator instead of the str function.

On a 500 by 500 array created via

result = []
for x in range(500):
	result.append(range(500))

I timed my version at 3 seconds, and your version at 12 seconds
(both including the array setup time).

On a 1000 by 1000 array, my version took 12 seconds and your version
took about 95 seconds.

-- 
Seth David Schoen <schoen@loyalty.org> | Its really terrible when FBI arrested
Temp.  http://www.loyalty.org/~schoen/ | hacker, who visited USA with peacefull
down:  http://www.loyalty.org/   (CAF) | mission -- to share his knowledge with
     http://www.freesklyarov.org/      | american nation.  (Ilya V. Vasilyev)