이 문제는 IE 6에서만 나타나는 문제이며 이로 인해 가시적으로 드러나는 현상는

이미지의 깜박거림이지만 더욱 치명적인 문제는 깜박거리는 현상이 발생할때마다 (또는 깜박거리지는 않더라도) 해당 이미지를 가지고 있는 서버로 이미지 전송 요청을 보내거나 local cache 를 access (file access) 하는  현상이 유발되고 이로인해 사용자 브라우저의 메모리 및 CPU 과다사용, 랜더링 속도 저하, working cursor(모래시계)로 마우스 커서 바뀌는 현상 등이 동반되므로 더 나은 서비스를 제공하고자 한다면 각별히 주의해야될 문제다.

이러한 현상은 일어나는 원인은 크게 두가지 유형 정도로 판단된다.

문제 1) href 속성이 주어진 A 태그가 있고 해당 A 태그 혹은 그 하위 element에 css로 background-image 를 적용하였을 경우, A 태그에 hover(마우스 오버, 포커스 이동 등)가 되면 A 태그와 그 하위에 있는 모든 element에 적용된 background-image가 - 같은 이미지 일지라도 element 수만큼 - 서버에 재요청되는 현상이 생긴다.
-> 깜박거림, working cursor등이 동반될 수 있다.

문제 코드1 보기

<html>
<head>
<title> test </title>
<style type="text/css">
span {
  background-image: url(test1.gif);
}
a {
  background-image: url(test2.gif);
}
</style>
</head>
<body>
<a href="#">
    <span>test</span>
    <span>test</span>
    <span>test</span>
    <span>test</span>
</a>
</body>
</html>

문제 2) 임의의 element에 css로 background-image 를 적용하였을 경우, onload이벤트 후에 해당 element나 그 상위 element의 style을 수정하면 해당 element에 적용된 background-image가 서버에 재요청되는 현상이 생긴다. 바꿔 말해서 onload 이후에 background-image가 적용된 부분을 포함하고 있는  element의 style을 바꾸면 해당 element와 그 하위에 있는 element들에 적용되어있는 모든 background-image가 - 같은 이미지 일지라도 element 수만큼 - 서버에 재요청 되는 현상이 생긴다.
-> 깜박거림, working cursor등이 동반될 수 있다.-> 깜박거림, working cursor등이 동반될 수 있다.


문제 코드2 보기

 
<html>
<head>
<title> test </title>
<style type="text/css">
#test {
  background-image: url(test1.gif);
}
span {
  background-image: url(test1.gif);
}

</style>
<script type="text/javascript">
function init() {
    document.getElementById('test').style.position = 'relative'
    document.getElementById('test').style.top = '1px'
    document.getElementById('test').style.left = '2px'
}
</script>
</head>
<body onload="init()">
<div id="test">
    <span>test</span>
    <span>test</span>
    <span>test</span>
    <span>test</span>
    <span>test</span>
</div>
</body>
</html>


문제1, 2를 완벽히 해결하는 방법.


사용자들에게 브라우저를 바꾸도록 강요할 수 있다면 IE6 이외의 브라우저를 사용하게 한다.
문자1, 2의 상황이 생기는 필요조건을 충족하지 않도록 코드를 바꾸는게 가능하다면 바꾼다.
  (ex. background-image를 사용하지 않은 css 혹은 img태그로 대체.)
하나마나한 얘기인가?. 그래도 모른다. 고민해보자.. 이 두가지가 가능한지.


문제1, 2가 일어나는 브라우저 범위를 줄이는 방법.

Internet Explorer 6 서비스 팩 1(Windows XP SP1) 이후의 브라우저에서는 "BackgroundImageCache" 라는 Command Identifier로 execCommand를 호출함으로써 이 문제들을 해결할 수 있다.
 - 서비스팩 2에서는 포함되어 있으며, 서비스 팩 1(6.00.2800.1106)은 update 유무에 따라 다를 수 있다. - 브라우저 버젼 확인 방법 ( http://support.microsoft.com/kb/164539/ko )

document.execCommand("BackgroundImageCache", false, true);

이 생소한 BackgroundImageCache라는 녀석은 MSDN에서 제공하고 있는 Command Identifiers list (http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/commandids.asp) 에서도 찾을 수 없다.

MSDN KB를 뒤진 결과.
 Available memory decreases when you view a Web page in Internet Explorer 6 Service Pack 1 (http://support.microsoft.com/kb/823727) 에서 이 녀석에 대한 언급을 볼 수 있었다. 이 문서에서 말하고 있는 해당 hotfix의 원인과 설명은 보든 안보든 달라질게 없는 쓸모없는 내용이다. 또한 "Document.ExecCommand" 처럼 대소문자 규칙까지 어기고 있다. 여튼 이 너저분한 내용의 hotfix와 그 해결 방식은 치명적일수도 있는 결함에 대한 MS의 궁여지책 같은 냄새가 짙다.
결론은 Internet Explorer 6 서비스 팩 1 이후의 브라우저에서만 이 문제를 해결하고자 한다면,
BackgroundImageCache Identifier가 없는 브라우져에서 발생할 수 있는 예외를 무시할 수 있는 코드가 첨가된 아래 코드만으로 충분하다.

Internet Explorer 6 서비스 팩 1(Windows XP SP1) 이후 브라우저를 위한 해결.

try {
    doument.execCommand("BackgroundImageCache", false, true);
} catch(ignored) {}

주의. 아래와 같은 해결방법에 대한 제시를 본적이 있다.
html {
    filter: expression(document.execCommand('BackgroundImageCache', false, true));
}
유사해 보이지만 다른 내용이다. 이 방식은 두가지 측면에서 좋지않다. 첫째는 BackgroundImageCache Identifier가 없는 브라우져에 대한 예외처리가 없다는 것이고, 둘째는 한번만 수행하면 되는 코드가 지속적으로 수행된다는 것이다.


구제받지 못한 IE6들을 위한 개선 방법

간단한 코드로 IE6 서비스팩 2와 서비스팩 1이후의 일부는 문제 대상에서 제외됐지만, 아직 서비스팩이 포함되지 않은 IE6가 방치되어 있다. 불행히도 이 브라우저들을 위한 간단한 해결책은 없는 듯하다. 그래서. 문제를 개선할 수 있는 방법을 정리한다.

개선 1. 브라우저와 서버의 통신을 줄인다.

방법 1.1. 사용자 브라우저의 임시 인터넷 파일 설정을 바꾸도록 한다.

브라우저의 임시 인터넷 파일 설정이 기본 설정값인 "페이지를 열때 마다" 일때 더 심각한 문제를 유발하므로 사용자에게 브라우저 설정을 바꾸는 것을 강요할 수 있는 상황이라면 그렇게 하라.
방법 1.2. 서버에서 expires나 cache-control헤더를 포함한 컨텐츠를 보내서 클라이언트의 local cache 사용을 유도한다.


서버설정참고 열기

 
아파치일 경우

httpd.conf 에 아래 내용을 추가

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/png A2592000

LoadModule expires_module modules/mod_expires.so

httpd.conf 를 수정할 수 없다면 자신의 .htaccess 파일을 수정한다. (단, mod_expires는 load되어 있어야한다)

설정방법 참고 : http://dean.edwards.name/my/flicker.html
mod_expires에 대한 설명 : http://httpd.apache.org/docs/2.2/ko/mod/mod_expires.html

IIS일 경우

아래의 헤더를 추가
Cache-Control: post-check=3600,pre-check=43200

설정방법 참고 : http://www.aspnetresources.com/blog/cache_control_extensions.aspx


서버 설정을 할 수 없다면 웹 어플리케이션 작성시 expires나 cache-control헤더를 클라이언트에게 보내는 코드를 추가하라.
이 방법들은 컨텐츠를 서버에서 받아간 후, 파기(expire)되는 기간까지 서버에 재요청하지 않고 local cache를 사용하게 하는 일반적인 웹어플리케이션 성능향상 팁이기도 하다.

위에서 제공 것은 개선 방법임을 다시 한번 강조한다. 절대. 해결 방법이 아니다. 원격서버와의 통신을 줄어드나 local cache에 대한 불필요한 접근들은 일부 방치된다. 어떤 것들이 방치되는지 궁금하다면.. 브라우저 프로세스가 여는 파일 핸들들을 감시해보라.

개선 2. 문제1에서의 이미지 깜박거림을 감소시킨다.

이 부분은 아래의 링크에 수록된 잼있는(?) 내용을 전제로 한다.
Minimize Flickering CSS Background Images in IE6  (http://www.fivesevensix.com/studies/ie6flicker/)

이 문서에서는 문제 1에서 발생하는 깜박거림에 대한 집요한 테스트 결과가 있다.

아래의 속성이 직접 적용되거나 상속되는 경우,
    background-color : transparent 이외의 값
    background-repeat : repeat 이외의 값
    background-position : 모든 값
또는
background-image가 적용된 element의 크기가 2500픽셀 미만일떄,
또는
투명 gif를 백그라운드 이미지로 사용했을때,

깜박거림 현상이 더 크게 발생하며

A태그의 상위엘리먼트에 같은 background-image를 지정해둠으로써 깜박 거림 현상을 감소시킬 수 있는 방법등을 제시하고 있다. 잼있는 개선방법중 하나지만 다른 개선이 배제된 상태에서의 이런 개선방법은 별로 추천하고 싶지는 않다.

개선 3. 문제2에 대한 개선

문제2에서의 특이한 사항은 특정 element의 style을 보정할때 style이 직접 대입되는 element는 그 대입횟수만큼 background-image를 다시 로딩하는 현상(download 혹은 local cache 접근) 이 생긴다는 것이다. 이와 달리 그것의 하위 element들은 상위element에 style이 대입되는 처음 시점에 단 한번의 불필요한 로딩만 다시 일어난다.

따라서 문제2를 조금 개선할 수 있는 방법은 style을 보정할 element에는 background-image css가 적용되어 있지 않게 하거나 뺄 수 없다면 불필요한 element로 싸는 정도의 간단하고 깔끔하지 못한 방법으로 문제를 축소시킬 수 있다.

모든 style 적용에서 테스트를 해본 것이 아니라. 항상 이 규칙이 적용된다는 보장은 할 수 없지만, 분명히 일반적인 위치이동 등의 처리에서는 개선되는 효과가 있다.

페이지에서 쿠키 값을 체크 하여 팝업을 열지 말지를 선택하는 소스이다.
자주 쓰이고 쉽게 검색 할 수 있는 소스이지만, 정리 차원에 써놨다.

팝업 페이지에 체크 박스의 체크 여부나, onClick 이벤트 등을 이용하여 쿠키값을 지정한다.
지정하는 방법은 아래와 같다.

<script language=javascript>
    function setCookie(name, value, expiredays) {
        var todayDate = new Date();
        todayDate.setDate( todayDate.getDate() + expiredays );
        document.cookie = name + "=" + escape( value ) + "; path=/; domain=.saramin.co.kr;
                                expires=" + todayDate.toGMTString() + ";"
    }
</script>

체크 박스를 이용한다면, 선택 되어 있는지 확인 후,
쿠키를 지정해 주면 된다. 그리고 self.close() 그러면 끝!!!

마지막으로 메인페이지에서 팝업 페이지를 열지의 여부는 쿠키값을 체크하여
팝업을 열어주면 된다.
쿠키 값을 체크하는 소스는 아래와 같다.

<script language=javascript> 
    function getCookie(sName) {
        var aCookie = document.cookie.split("; ");
        for (var i=0; i < aCookie.length; i++) {
            var aCrumb = aCookie[i].split("=");
            if (sName == aCrumb[0]) {
                return unescape(aCrumb[1]);
            }
       }
       return "";
    }
</script>


ASP.NET Performance Tips

At times even after applying the best coding policies & practices you don’t get the desired level of performance you are hoping from your ASP.NET application. This is because there are number other very important factors that directly affect ASP.NET applications. To get the best out of any system requires detail architectural, design, coding and deployment considerations. The post lists few of some of the many performance tweaks that you can implement to boost up ASP.NET performance.

Remove Unused HTTP Modules

There are various HTTP modules in ASP.NET that intercept each request sent to the server. Session State is a very commonly used HTTP module used to load session data in context object. It’s referred with SessionStateModule name. HTTP modules kick in at each request and process them, therefore if you are not using the functionality provided by the module there is no use referring it as they would use additional CPU cycles. There is a list of HTTP Modules that your application automatically uses when it inherits config setting from web.config placed in $WindowsFolder\Microsoft.NET\Framework\$versiosn\CONFIG folder.
Below is a list of such entries:

<httpModules>
  <add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
  <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
  <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"/>
  <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
  <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/>
  <add name="RoleManager" type="System.Web.Security.RoleManagerModule"/>
  <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
  <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/>
  <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/>
  <add name="Profile" type="System.Web.Profile.ProfileModule"/>
  <add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  <add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</httpModules>

There are bunch of HTTP modules listed here and I am quite positive not all of them are being used by your application. Removing unused HTTP module can definitely give slight performance boost as there would be less work to be performed. Suppose one doesn’t needs Windows authentication in application. To remove the inherited setting, under httpModules section in your web.config application add a remove element and specify name of the module that isn’t required.

Example:
      <httpModules>
            <remove name="WindowsAuthentication" />
      </httpModules>

<compilation debug=”true”/> Killer
As a developer I have seen numerous incidents were the application is deployed to production with <compilation debug=”true”/>. This is really a performance killer because:
  • Compilation of ASP.NET pages take longer.
  • Code execute slower as debug paths are enabled.
  • More memory is used by the application.
  • Scripts and images from WebResource.axd handler are not cached.

Always make sure that debug flag is set to false on production instances. You can override this by specifying following entry in machine.config for production instances:

      <configuration>
            <system.web>
                    <deployment retail=true/>
            </system.web>
      </configuration>

This will disable the <compilation debug=”true”/> for all applications deployed on the server.

Turn off Tracing

Do remember to turn off tracing before deploying application to production. Tracing adds additional overload to your application which is not required in production environment. To disable tracing use the following entries:

      <configuration>
            <system.web>
                    <trace enabled="false" />
            </system.web>
      </configuration>

Process Model Optimization
ASP.NET allows you to define many process level properties. You can get the detail of all these properties from http://msdn.microsoft.com/en-us/library/7w2sway1.aspx.  By default these are set to auto config. This means that ASP.NET automatically configures maxWorkerThreads, maxIoThreads, minFreeThreads, minLocalRequestFreeThreads and maxConnection to achieve optimal performance. You can tailor these by specifying your own value to achieve better performance. Some of the major settings are:
  • maxWorkerThreads. The default value is 20 per process and it determines the maximum number for request that ASP.NET can process in a given second. For application that are not CPU intensive and most of time wait on database request or any external processing this can increased to get better performance.
  • maxIOThreads. The default value is 20 per process and it determines the maximum number for I/O request that ASP.NET can process in a given second. If you have enough I/O resources you can increase this value for better results.
  • memoryLimit: The default is 60%. This is the max memory ASP.NET can use until worker process is refreshed. If you have a dedicated web server with no other services running you can increase this value for better results. 
  • connectionManagement: This is a property of System.Net configuration and specifies the maximum parallel connections that can be established to a server. If your web application extensively connects to other server you can increase this value.
Enable Buffering

Make sure that buffering is enabled unless you have a specific need to turn it off. By default its enabled. ASP.Net sends response to IIS in a 31 KB buffer which then passes that to the client. When buffering is disabled ASP.NET only sends few characters to IIS thus not utilizing this buffer and increasing the trips between IIS and the worker process. To enable it you can change the web.config or enable it on each page through @page directive

      <pages buffer="true">

      <%@ Page Buffer="true"%>

Caching
Caching in ASP.NET dramatically help in boosting application performance by reducing the load on the underlying server and serving cached content that doesn’t need to be recreated on each request. ASP.NET provides two types of caching:
  • Output Cache which stores dynamic pages and user controls. One each request code is not executed if a cached version of page or control is available 
  • Data Cache which allows application to save application objects, DataSet etc in server memory so they are not recreated on each request.

Use caching whenever possible to reduce the load on your web server and to increase response time.

Caching is a huge topic can not be discussed in detail in one post. For more details visit http://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx.

Kernel Cache
Use Kernel Cache if you are using IIS 6 or above. When Output cache is used in ASP.NET the request still goes to ASP.NET that itself returns the cached content. However if Kernel Cache is enabled and the request is output cached by ASP.NET, IIS receives the cached content. If a request comes for that data again IIS will serve the cached content and end the response. This can save valuable CPU cycles as it minimizes work performed by ASP.NET.

Avoid using Response.Redirect
Instead of using Response.Redirect, use Server.Transfer where ever you can. Response.Redirect sends response to the client which then sends a new request to the server. Server.Transfer however performs the redirect on the server. Only use Response.Redirect when you want authentication and authorization to be performed on redirects or you want URL on client browser to be changed because Server.Transfer will not do this as it is a server side transfer.

Avoid using Server-Side Validation
Where ever you can use client-side validation instead of Server-Side validation. This will save you from additional reposts in cases in invalid input. If you don’t trust the browsers that they will be able to perform complex validations still use client-side validation and on repost check Page.IsValid to check if the input passed the given set of rules.

Avoid DataBinder.Eval Calls
Avoid calling DataBinder.Eval multiple times for example in case of grids, repeaters etc. Instead use Continer.DataBind. DataBinder.Eval uses reflection to evaluate the arguments and therefore can decrease performance if called numerous times.

Avoid Using Page.DataBind
Never call Page.DataBind until your really need to do so. Instead if you want to bind a specific control only bind that. Calling Page.DataBind will call DataBind for all the controls that support binding.

ViewState Optimization
Avoid using ViewState for storing huge objects or disable it when you don’t need it. ViewState is also used by server controls so that they can retain their state after postback. You can also save your objects that are marked Serializable in the ViewState. ASP.NET serializes all objects and controls in the ViewState and transmits them in a hidden field to the browser. If not managed properly ViewState can increase page size and therefore increase network traffic. Also precious CPU cycles are used for Serialization and De-Serialization of ViewState objects. Disable ViewState if:
  • Your pages don’t do postback.
  • You controls are not bound to a data source or they don’t handle server events like OnClick, OnSelectedIndexChanged etc or their properties are set on each postback
  • You recreate controls on every postback.

You can disable ViewState in both web.config or @Page directive

      <pages enableViewState="false">
      or
      <%@ Page EnableViewState="false"%>

Save or Compress ViewState
In case where ViewState in mandatory and the ViewState contains enough data that can cause Network congestion or increase download response time for the user try saving or compressing the ViewState. The Page class provide two very useful methods LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium(object ViewState). You can override these methods to either compress the ViewState or even prevent it from going to the client by saving it in some persistent medium on the server.

Use HTTP Compression
If your page size is large enough to cause noticeable lag between subsequent request and response you can use HTTP compression. HTTP compression is a feature of IIS and what it means is that you can compress data sent to the client using compression techniques like GZIP and Deflate. On the other side the browser decompresses the data and shows the response to the client. Most of the modern browser are capable of handling compressed data. You will certainly get a huge performance boost if your page size is large.

For more details on HTTP compression visit http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d52ff289-94d3-4085-bc4e-24eb4f312e0e.mspx?mfr=true

Data Paging / Sorting
When ever using data grid to show data with paging enabled one thing needs to understood that if your query returned let say 5000 record and you are only showing 100 records per page the rest of the 4900 record will be discarding and the same will apply when ever you will change the page or apply sorting. The additional 4900 rows will definitely take up memory and if your database is located on a different server which is most commonly the case you will also be transferring unnecessary data over the network. Make sure you are only returning the required results to the ASP.NET application by filtering out the data in your database query and apply custom paging. SQL Server 2005 and onwards provide valuable function for ranking data that can be used to accomplish this.

Connection Pooling
Creating a connection to a database is a resource intensive process and takes time. Connection pooling allows you to reuse these connections saving time and resources. When a new connection is requested the connection pool managers first searches in the connection pool and if doesn’t finds one, it creates a new one. There are various things that need to be done to use connection pooling effectively:
  • Avoid Connection Leakage. This means that you opened a connection but didn’t close it. If you don’t close the connection the connection pool manager will never put it in the pool for later reuse until the GC is called.
  • Use the same connection string. Connection pool manager searches for similar connection in the pool by the connection string.
  • Use SQL Servers and .NET CLR Data performance counters to monitor pooling.
  • Open connections as late as possible and close them as early as possible
  • Don’t share same connection between multiple function calls. Instead open a new connection and close it in each function.
  • Close transactions prior to closing the connection.
  • Keep at least one connection open to maintain the connection pool.

Avoid Multiple Database Access
Avoid accessing database multiple times for the same request. Analyze your code and see if you can reduce the number of trips to database because these trips reduce the number of request per second your application can serve. You can do this by returning multiple records in the same stored proc, combining multiple DB operations in same stored proc etc.

Use DataReader Instead of DataSet
Use DataReader objects instead of DataSet when ever you need to display data. DataReader is the most efficient means of data retrieval as they are read and forward only. DataSet are disconnected and in-memory therefore uses valuable server resources. Only use them when you need the same data more then once or want to do some processing on the data.

Last but certainly not the least follow the best coding, design and deployment patterns and practices. Here are few more usefull links that can be very helpful in performance optimization of you ASP.NET application

+ Recent posts