Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Optimize your code 8

Status
Not open for further replies.

vasah20

Programmer
Feb 16, 2001
559
US
Now, I don't claim to have all the answers, nor will I say that all my answers are correct, but what this post is about are the ways to optimize your code. These are just things that I have observed either through practice, or read somewhere. I have linked this to an FAQ, but the reason that I have made this into a post is because I want this document to grow. Like I said, I don't know all the possible ways to optimize your application... I was hoping to get some help from the other members through their additions to this post. This is presented in completely random order.

Data source
- Just by optimizing your database, you can gain some significant speed.
- If you use a DB that supports Stored Procedures, USE THEM RELIGOUSLY. Not only will your ASP code see a significant speed increase, it also becomes alot easier to update your application.
- If you use something like Access, realize that the more joins you have, the less efficient your query will be. This comes with a tradeoff though, since you lose a lot of the natural benefits of normalizing your database.
- Don't do "SELECT * ..." if you don't need all the columns. Specify the columns you need, it saves processing time.

File extensions
- If your page does not have any ASP code on it, do not save it with an .asp extension, save it as .htm or .html.
- If your page has no ASP code, but only has include directives, save it with a .shtm or .shtml extension.
- This is good because if you don't need the dll's functionality, then don't incur the overhead of loading the asp or include processing dlls.

Global.asa
- If you use adovbs.inc anywhere, load the type library. The speed change for this is immediately noticed. Thanks to link9 for bringing this point to light. If you need to know how to load the adovbs.inc meta library, check thread333-81602.
- Do not give ADO Connection objects Application or Session state. Doing so increases the thread affinity and reduces the application's scalability.
- Do store your connection strings in the Global.asa. This isn't a steadfast speed increase, but I've always found that it makes life a whole lot easier when you change anything in your data access technique.

Read this

I'll probably end up reiterating points that were stated in the MSDN article, but I know that I won't cover everything. Read it for some great optimization tips.

ASP Code
- Avoid string concatination in VBScript. It's extremely slow... if you need to do heavy string concatination, use a separate component for it.
- If you're willing to do it, use JScript for your pages. I've read benchmarks where JScript outperforms VBScript in every category except for string manipulation. Unfortunately, alot of legacy ASP code and most of the examples you see out are in VBS.
- Use functions. Don't give variables page scope if they don't need it. Give them local scope, and it should be easier on your application. Plus, you can reuse 'i' ;) (for i = 0 to ...)
- Use Option Explicit. Not only does it help your app speed, it also helps you debug.
- If IIS is setup to use VBScript as it's default scripting language, remove the <%@LANGUAGE=VBScript%> from the top of your pages. Again, why process server-side directives if you don't need to. If you use JScript, specify it as your default IIS language, then remove the @LANGUAGE directive.

ASP objects
- When using Request, specify .Form or .QueryString. I've heard there is a slight performance hit by not specifying the collection, so specify the collection. I only use Request(&quot;..&quot;) when absolutely necessary.
- Concatinate your Response.writes. If you concat a string, then response.write that string, see if there's a way you can just write everything out to the screen. You avoid the overhead of string concatination, which is a very good thing.
- Use Response.buffer at the beginning of your pages. This way IIS can process the entire page then output to the browser, as opposed to sending the output as it's done. If you need to show some of the page, use Response.Flush to flush out the contents.
- Only create objects if you need them. Also, set all objects = nothing when you are done with them.

ADO Objects
This is where you should be able to get the most performance increases. The connection stuff is especially important regarding people who have Access databases on the backend. Access cannot handle multiple current connections very effectively, so you need to try to keep your connections open as little as possible.
- If you are updating your DB, do not use the recordset to issue the update. Instead, use conn.execute sqlstatement. It'll save you the cost of creating the recordset object when you don't need to. Remember, that Access 2000 allows you to get @@IDENTITY, so if you need the just inserted pk, you can get it that way.
- Use .GetRows and .GetString. Using both allow you to get all of the rs information stored into memory, then you can free up the connection and recordset objects very quickly.
- If you need to do a lot of recordset manipulation, consider disconnecting the recordset from the data source.

I *know* there are other ways to optimize your ASP... I just can't think of them now. Please -- if there's anything else that you know, contribute to this post.

hth someone
leo
 
one thing i would note in this FAQ is that JScript has no counterpart to the Option Explicit statement. Unrecognized variables are automatically declared when they are defined.
 
Nice tips.. as a new coder I have learned a few things more that will help a lot! Thanks!
 
Something else I thought of:

Cache Frequently Used Data
- If you get the results of a recordset numerous times, and these results never change, cache them into an Application variable. What I would do is cache the results of a .GetRows, then access that App variable whenever necessary.
- For a great example of caching, see
 
i thought i saw a thread on this already, but can't find it now, so i'll ask....

does anybody have any facts, or opinions, on using <% %> on every line of code, vs. using just at the start and end of blocks of code.

thank you very much all, in advance, for your responses!
 
I thought that the less you jump in and out of asp code the faster you'll process the pages. I would go with the <% %> at the start and end of blocks of code whenever you can.

Also, in place of session variables I normally use cookies whenever possible.
 
so you would recommend:

<%
'Form variables
Dim iJob_Id
Dim sDate
Dim sJob_Code
Dim sTitle
Dim sLocation
Dim sDescription
Dim sRequirement
Dim iGroup_Id
Dim sStatus
Dim sHome_Page
%>

over:

<% 'Form variables %>
<% Dim iJob_Id %>
<% Dim sDate %>
<% Dim sJob_Code %>
<% Dim sTitle %>
<% Dim sLocation %>
<% Dim sDescription %>
<% Dim sRequirement %>
<% Dim iGroup_Id %>
<% Dim sStatus %>
<% Dim sHome_Page %>

??

anywhere in writing that would support that? kinda got an office bet riding on this.... ;-)
 
I cache data as well, but I don't use application variables to do it, since there is more than I really want to cache.

I have some data that regularly changes, but not in any significant way. So once an hour, the information is refreshed, or sometimes two or three hours later. It's refreshed any time someone logs in and it's been over an hour since last refresh.

At that point, the information is polled from the database and written to an include file as a dictionary.

Any other time, it's just pulled out of the dictionary!

I like that idea =)

As fro using <% %> on each line, I would avoid it myself as well. As far as I can tell, each time the asp engine reaches a %> tag it reverts to the html engine until it hits <% again. So I believe, but am not sure, that it would flip flop for no reason at the end of each line.

--chajadan
 
Lobstah, I don't know where it is in writing, but I can tell you this. Every time you put those tags, it's like flipping a switch.

ON-OFF
ON-OFF
ON-OFF
ON-OFF
ON-OFF
ON-OFF

--or--

ON-OFF

What's more efficient?

If you bet on the single opening, and single closing, then you win the bet. ;-)
penny.gif
penny.gif
 
I read the Microsoft 25+ tips article above. Very enlightening. But I'm still confused over some things in there...

1. Is it really true that we should set all local variables = Nothing at the end of every page to optimize code? The article said we should &quot;set VBScript variables = Nothing&quot;.

2. How much memory (or how many characters) can a Session variable contain?

Thanks for the help!
 
Local Variables: Not all local variables, just all objects. Rather than waiting for the engine to get around to cleaning up after itself it is a beter idea to dereference these objects so they will get released from memory quicker. This includes things like ADO objects, FileSystem objects, etc but not necessarally variables like that sql string variable 30 lines earlier in your code.

Memory: Session variables are stored on RAM :) As to a maximum amount it can hold, I haven't seen a documented figure, but I'll do a little research and see what turns up.



-Tarwn --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
 
Thanks Tarwn. That's a relief to hear! :)
 
Since we are the topic of optimization, I thought that I would add the string optimization class.

Code:
' PURPOSE: 	This is a string optimization class when working with large
'			string concatenations. This class will dramatically speed
'			the process of concatenating strings.
' 			
' ABOUT: 	VB and VBScript have intrinsic array functions such as JOIN that are, 
'			MUCH FASTER at concatenating variant array elements. This class keeps our 
'			string information in an array (its always a Variant anyway, so what's the 
'			difference?) and then when we're finished with all of our concatenations we 
'			have it just do a JOIN on the array with NO DELIMITER so it all comes back 
'			as ONE BIG LONG STRING, in a SINGLE OPERATION.
'
' USAGE:	Set objStrOpt = New StringOptimizer
'			objStrOpt.Reset
'			objStrOpt.Append &quot;String1&quot;
'			objStrOpt.Append &quot;String2&quot;
'			objStrOpt.Append &quot;Stringx&quot;
'			Response.write(objStrOpt.Concat)
Class StringOptimizer
	Dim stringArray,growthRate,numItems

	Private Sub Class_Initialize()
		growthRate = 50: numItems = 0
		ReDim stringArray(growthRate)
	End Sub

	Public Sub Append(ByVal strValue)
		' next line prevents type mismatch error if strValue is null. Performance hit is negligible.
		strValue=strValue & &quot;&quot;
	
		If numItems > UBound(stringArray) Then ReDim Preserve stringArray(UBound(stringArray) + growthRate)
		stringArray(numItems) = strValue: numItems = numItems + 1

	End Sub

	Public Sub Reset
		Erase stringArray
		Class_Initialize
	End Sub

	Public Function Concat() 
		Redim Preserve stringArray(numItems) 
		Concat = Join(stringArray, &quot;&quot;)
	End Function

End Class
_______________________________
regards,
Brian

AOL IM: FreelanceGaines

AG00280_.gif
 
To improve performance we can also do the following:

Prior to the &quot;do while not rs.eof&quot; bit in our code we can do the following, which will read the field object into an object variable, then the object reference is used to get the value from the database. For example:

Code:
Set UserName = rs(&quot;userName&quot;)
Set UserEmail = rs(&quot;userEmail&quot;
Set UserState = rs(&quot;userState&quot;)

do while not rs.EOF
  response.write &quot;Name: &quot; & UserName & &quot;<br/>&quot;
  response.write &quot;Email: &quot; & UserEmail & &quot;<br/>&quot;
  response.write &quot;State: &quot; & UserState & &quot;<br/>&quot;
  rs.MoveNext
loop
Hope this helps some people out there improve there site performance. My daily story these days:
9am [pc2] => 3p [flush] => 6p [pc2] => 10p [yawn2] 12a [hammer] => 1a [pc1] 3a [sleeping] => fri [cheers]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top