Retouch! I would say – why not? February 6, 2010 1 Comment
Its less of a risk then getting yourself a liposuction or a nasty boob job
..
Before I answer WHY let me answer WHAT! For all of you who don’t know what I am talking about watch this video “The Photoshop Effect”
Why Retouching
On a serious note, Human psyche has been on a constant Endeavour to achieve perfection. Retouching is a means to persue that human pursuit. How else would you preserve and portray the invaluable momentary short lived tequila shots of your life. A retouched image would give you that well deserved kick time and again.
Besides not all of us can carry a Cindy Crawford mole as a beauty spot the way she does. Come on, would you want that dark spot seen in your wedding snaps. You would rather get them retouched. Similarly you would more often then not, want to get a brighter retouch-er if you are from the Naomi Campbell or a Hale Berry progeny. "I don’t mean to be a racist here" unless you want to spend a bomb to look as good.
Retouching the History
Beginning from our inception, Adam was perfect as a first masterpiece, as a human being, but as a man he was lacking. Later, Adam with Eve became a perfect couple until they fell prey to Satan’s handiwork and since then we’ve been living in an imperfect world. I need not elaborate on this any further and no wonder everything around us is (believe it or not) imperfect.
Retouched – Do We Even Know?
BTW If you see a problem here, sure do something, lets run a campaign to make it a mandate to put an * (asterisk) symbol on every retouched image. I bet you would see 99.9 % of photographs retouched in any magazine or billboard or for that matter any print media with an asterisk sign, the way we notice "*" or "Conditions Apply" on every shop running a SALE.
Lately there has been a lot of hype around retouching and its adverse effect or so they call it, just because some nuts went on an indefinite dieting spree to fulfill there fantasies of attaining that perfection portrayed by a retouched image of a model. I have a question here, if some one ignores that ‘asterisk’ on a FOR SALE sign board and happens to pick up stuff and queued up at the counter only to realize that there was some other exception, what do you think would happen. Wouldn’t you ask her to go back to shopping basics. She’s not duped! An asterisk is supposed to be taken for granted.
Retouching & The Craving Need of It
As I proclaimed above I see no moral hang-up in retouching a photo but the reality is that it can change a picture from something you dislike to something enjoyable. We all understand the difference between tweaking the truth and portraying the expected. Perfect moments do not always prove to be perfect and that’s where we need the so called digital liposuction.
Let me sum up with a practical example:
A stunning model sitting right in front of you that has potential but several flaws. By several I mean the following two major flaws apart from a few here and there that can otherwise be taken care of:
Dull Hair
has a pimple right on the face of the camera lights
What do you do ?
1) Hand over the best shampoo available and wait for the results + wait for the pimple to even out.
2) Click the snap and retouch it. Its simple and worth while.
I leave it for you guys to decide. Any takers!!
For all of you guys who want to try the first option you need to keep visiting my blogs for the rest I know you guys understand how difficult it is to get a boob job done, and how difficult it is to get that perfect look unless we go to RetouchMAX.com
Current Problems of Windows 7 for Developers September 13, 2009 1 Comment
After visiting Microsoft TechNet Seminar everyone was quite excited about Windows 7 and everyone was saying that Windows 7 is far better then Vista and its now ready to go alive. I did stick to my plan of upgrading my development machine to Windows 7 only after Service Pack 1 arrives. But everybody argued that no its ready for developers even. Fine I tried to install it on my laptop which I rarely use for development and here is the experience.
It took drivers and it was pretty faster then Vista as far as installation goes, but then immediately I found two problems.
Move Files Progress Bar Bug
I took backup on my other D drive and I have both administrator and basic user and while copying files back on basic user I found this bug. When you are trying to move files, and if you are an administrator and it doesnt need any UAC permissions then you can see progress bar as shown below.

But if your destination folder/drive requires some UAC permission then the UAC dialog box comes and when you accept everything after that the progress bar no longer displays progress as shown below.

This happens if you try to copy something into windows/program files or anywhere for some other users when running from basic user.
And we have to wait endlessly for this window to get closed automatically and that probably proves that operation was successful.
I am really disappointed to see bugs on very critical operations like file operations are most crucial. Even on Vista, Move operation did not work correctly as it did not delete the source files/folders and that leaves us with confusion.
Canceling Move Operation Creates Inconsistencies
While the Move operation is on, if you decide to cancel, you are left in bad position because then you are left with half files from old location and half in new. Sure its not great problem as we can consolidate immediately.
Cant Install Remote Server Administration Tools (RSAT)
This is really great bug, because on development machine, we really cant live without RSAT. We need them to manage servers. I found this link from live search, RSAT for Windows 7 . When I try to install this update it gave this error message “This update is not applicable for your computer”. Further more in Event Viewer, I got this message.
Windows update could not be installed because of error 2149842967
I did report this bug to lot of places, hope it gets resolved soon, but I think on Microsoft Download website they should put some feedback about the item being downloaded.
Visual Studio 2008 Installation Problems
I am not sure whether VS 2008 installed successfully or not, because although it said it was successful, there were certain errors in Event Viewer.
Product: Microsoft Visual Studio 2008 Professional Edition – ENU — Error 1935.An error occurred during the installation of assembly ‘Microsoft.Windows.Design,
version=”3.5.0.0″,
publicKeyToken=”b03f5f7f11d50a3a”,
processorArchitecture=”MSIL”,
fileVersion=”9.0.30729.1″,
culture=”neutral”‘.
Please refer to Help and Support for more information. HRESULT: 0×80070005. assembly interface: IAssemblyCacheItem, function: Commit, component: {7A515F16-7D3F-4A41-910A-E704ABC9E8CA}
I havent yet started using VS on 7 but I will soon and I am sure there will be many problems.
Cant Install Visual Studio 2008 Service Pack 1
However when I tried to install Visual Studio 2008 Serivce Pack 1, it didnt install and gave following errors in log.
Product: Microsoft Visual Studio 2008 Professional Edition – ENU – Update ‘KB945140′ could not be installed. Error code 1603.
And another error at the last,
Product: Microsoft Visual Studio 2008 Professional Edition – ENU – Update ‘Visual C++ 2008 SP1 Design-Time Components for x86 – KB947888′ could not be installed. Error code 1603. Additional information is available in the log file C:\Users\***\AppData\Local\Temp\Microsoft Visual Studio 2008 SP1_20090913_140916022-Microsoft Visual Studio 2008 Professional Edition – ENU-MSP0.txt.
Cant Install SQL 2008 Management Tools
I tried to install SQL 2008 Management Tools, it gave me compatibility issue and warned me that you must install SQL 2008 SP 1, I agreed. And I went ahead with installation and Installation stopped because Visual Studio 2008 SP 1 was not installed.
Conclusion
I think I am on conclusion that Windows 7 is not yet ready for Developers and they should wait for Windows 7 SP1 to arrive. And it should only be used by Testing Teams to test the products.
Optimize Windows Vista Machine for Faster Development (VC#,Web and VC++) August 29, 2009 No Comments
This document only refers to optimization of Vista Machine for faster development only intended for the ones who are doing development on C#, ASP.NET and Optional VC++, no VB.NET.
Installation of Limited Visual Studio 2008
We probably dont need Compact Frameworks and VB.NET and other tools, unnecessary installing them doesnt waste much of Hard disk space but what happens that your registry grows too big as you install more number of items. Registry is very costly database, and its accessed very regularly, more items in registry, slower and slower the PC. So here is list of items you should install.
Disable High End Graphics, Faster Performance
Disable System Restore Points
Now, System Restore Points are good, but usually on development machine, they run very slow, and they never do any good if system crashes, the restore time is as big as and as problematic as to reinstall OS.
Increase Paging Size
Increase it as much as you can in different drive but the acceptable range is 2GB to 4GB only.
Remove Unnecessary Vista Items as shown below
Setup Taskbar and Start Menu

Taskbar and Startmenu Properties
Expand Items for Quicker Use

Expand Control Panel

Expand Documents

Expand Admin Tools
Huge File Storage in Database instead of File System August 23, 2009 11 Comments
The quest to store large number of files in database or on regular file system began at a time when number of files to manage went beyond 1 million in one of our project. We started noticing a huge drop in performance of our windows server. After investigating we found out that using pure file system to store more then million files is really a bad solution. And following are key points.
- Each operation of file open/close requires kernel operation, because it needs to do various security checks.
- Every file operation requires some minimum locking mechanism which uses your cpu in kernel mode.
- Above operations being kernel operations, they slow down entire server even if your file access may be of least priority then any transactional database operation.
- Each services on server slows down.
- Even operating system itself manages a file system database (typically known as File Allocation Table and similar names in other systems).
- These databases are optimized but not for millions or trillions files. They are good to work under million files.
- It causes huge fragmentation on your storage media.
- Not only media, but even File System Database gets fragmented, leading to more slow down.
- Durability of storage media also can reduce because of too much fragmented usage.
- Backup and Restore operations take too long time. You can easily conduct an experiment, on any ftp client, try to upload only one 1Meg file and then try to upload 100 10KB files, although the total transfer is only 1Meg, you will notice uploading 100 files of smaller size takes longer.
- Keeping track of changes/deleted items are even more difficult.
- Tools for replication and change tracking for file systems aren’t available for huge file storages.
- The web server will need write access to some folders which is always a big security hole.
- And file system crash = operating system crash and thats a huge challenge to bring it back up.
- For transferring files you need to open ftp and develop some tools to replicate them.
Finally, after all these observations, we started considering other options.
- Network File System, it looks promising, but even at other end of node, its simply an operating system. It still has same problems as mentioned above.
- Distributed File Systems like Hadoop and other tools require too much of learning, management and I think they are good when you need file storage as huge as Facebook, Yahoo etc. We are mid size company and our need is 1TB for now.
Database Solution:
Finally we began testing database solution with MySQL and then we moved onto MS SQL, however both have good advantages and disadvantages that we will discuss further.
We have following advantages over file systems, and also I have provided solution detail later on this article.
- Database systems have matured enough to handle large data easily today.
- They use small number of files to store all relational data in well organized form.
- They keep their database files open all the time, so the kernel operations of locks are reduced.
- You can consider as if your load of entire server is now concentrated only on your database.
- Databases are much advanced in terms of their scheduling of queries, you can reduce priority of your file database and database will easily offer more performance on other transactional databases.
- Data storage is transactional, where else file systems are not completely transactional. And file systems require more programming to make them transactional.
- Remember if its your customers data, even if its a small picture/icon any video.. if they are paying for your service then its better to store those media files in transactional storage.
- Database crash doesnt crash entire server and nor even other databases on same server.
- Backing up and restoring databases are easier because of the inbuilt tools.
- Replication on database are much easier.
- Change tracking is available on database.
- Database access is standard its not dependent on ftp/http like tools.
- Database can easily take over failures of neighbor nodes in network.
- You can easily query database and do multiple operations on files.
- The biggest point is, your web server does not need any write permission on any folder !!
Comparison between MySQL and MSSQL for file storage
- MySQL offers replication over internet, MSSQL doesnt, you will have to write your own replication program.
- MSSQL offers auto grow option for database file, with which you can reduce fragmentation. MySQL’s innodb doesnt have such option for database file auto grow method which leads to more fragmentation.
- MSSQL offers easy incremental backup/restore and more over, in case of crash, you can use actual data folder files to restore, where else MySQL’s innodb doesnt support hot backups so either you buy their hotbackup tool or rely on mysql’s backup tool which is not incremental.
- MSSQL costs $1600 for standard edition, where else MySQL innodb is free, but hotbackup or incremental backup tools will cost exactly the same. MSSQL wins over mysql for offering better file management and increasing disc durability.
Sample Solution
After reading various articles, we came to conclusion that storing entire file in one blob or image doesnt make sense as it will deteriorate performance like anything.
So we came with easy solution, which is already used by existing file systems. Thats “Breaking down file into smaller blobs, max 512kb”.
As MySQL and MSSQL both have network packet size limit, you should not store more then 512kb in one row. Otherwise you will have to increase network packet size and that will slow down database server. Following is easy small table structure we used.
Table: NSFiles
NSFileID (Auto Number) (bigint)
NSFileName (varchar 50)
NSContentType (varchar 100) ** This is most important for web access
Table: NSFileBlobs
NSFileBlobID (Auto Number) (bigint)
NSFileID (bigint) (indexed) (Reference of NSFiles.NSFileID)
NSBlobIndex (int)
NSBlobData (medium blob or image)
Following are Storage/Retrieval methods specified in C# with using Linq or any similar ORML tool.
//Upload Handler
NSFile file = new NSFile();
file.NSFileName = .....
file.NSContentType = Request.Files[0].ContentType;
file.Insert(); // <-- insert into database and get new unique NSFileID
byte[] buf = new byte[512000];
int i = 0;
using(MemoryStream ms = new MemoryStream(Request.Files[0].FileData))
{
int count = ms.Read(buf,0,512000);
while(count>0)
{
NSFileBlob blob = new NSFileBlob();
blob.NSFileID = file.NSFileID;
blob.NSBlobIndex = i++;
if(count==512000)
{
blob.NSBlobData = buf;
}
else
{ // last blob will always be less then 512kb
blob.NSBlobData = new byte[count];
Buffer.BlockCopy(buf, 0 , blob.NSBlobData, 0 , count);
}
blob.Insert();
}
}
And following is simple code for Download Handler
// Download Handler
long fileID = long.Parse(Request.QueryString["FileID"]);
NSFile file = NSFile.Adapter.Get(fileID);
Response.ContentType = file.NSContentType; // important for web browser
// following line causes "Save As" box on client
Response.AddHeader("content-disposition","attachment;filename=\"" + file.NSFileName + "\"");
// following loops over all file blobs whose NSFileID is fileID and they are sorted by blob index
NSFileBlob.Adapter.ForEach(
NSFileBlob.Schema.NSFileID == fileID,
NSFileBlob.Schema.NSBlobIndex.SortAs(),
(t)=>{
Response.OutputStream.Write(t.NSBlobData,0,t.NSBlobData.Length);
}
);
C# Optimizations Via Caching – Part 2 March 22, 2009 1 Comment
I decided to write part 2 of optimization, with C# Project, to actually test the performance for accessing NameValueCollection and Property access.
I had lot of comments by extra smart people quoting regarding my previous post at "C# Optimizations Via Caching" . That all methods posted do not do any significant impact on performance, I wonder people just have habit of posting any thing without even thinking once.
So I decided to write a piece of code to actually demonstrate the optimization impact with statistics. In this Visual Studio 2008 C# Console Project, I wrote a simple code to access an application config value directly for 10,000 times in a loop and then to access it via statically cached variable. And in second part, I implemented accessing property and accessing a local variable nearly 10 million times to detect noticeable effect.
The tests are as follow,
Lets look at the test code to access config values, also please note that config values are stored in NameValueCollection, which is same object used in Request, Response and Session objects in web request.
// Configuration Access Test Console.WriteLine("Testing Direct Config Access"); Test(1000000, () => { string v = System.Configuration.ConfigurationManager.AppSettings["Key"]; }); Console.WriteLine("Testing Cached Access"); Test(1000000, () => { string v = SettingVal; });
Following is the result, on Intel Centrino Duo with 1GB of RAM, this shows that the code with cached access in static variable is 100 times faster.
Testing Direct Config Access
Time Difference 1125 MilSecsTesting Cached Access
Time Difference 15.625 MilSecs
So now next time you code, remember it to not access frequently in loops.
Lets talk about property access,
// Property in Loop Test int pc = 10000000; Console.WriteLine("Testing Direct Property Access"); Test(() => { Person p1 = new Person(); for (int i = 0; i < pc; i++) { string v = p1.Name; } }); Console.WriteLine("Testing Local Variable Access"); Test(() => { Person p1 = new Person(); string t = p1.Name; for (int i = 0; i < pc; i++) { string v = t; } });
In order to detect any noticeable difference, we have to loop for about 10 million times, however, in any usual code, you will be accessing 100s of properties, so it may make a good difference when you write code, which executes million times parallel.
Testing Direct Property Access
Time Difference 140.625 MilSecsTesting Local Variable Access
Time Difference 46.875 MilSecs
Now based on the amount of free memory, and cpu speed, you might have to configure the number of iterations up and down to get a good noticeable effect of two different ways.
I can clearly see the difference, remember on normal piece of code, you will be accessing over 10 to 100s of properties again and again.
Click on Caching Stats Visual Studio Project to download and test by yourself.
Day and Night time format March 7, 2009 No Comments
Conventional AM/PM time format is very confusing. At NeuroSpeech we decided to use new format to distinguish visually the day and night format. Rules are as follow,
1. Day time is considered between morning 6 to evening 5.59 as assuming range of average sun shined day.
2. Night time is considered as 6 of evening till 5.59 of next day morning.
Representations:
Print and computer
White background:
1. Day time should be written with black box around the time and white background inside the box with black text color.
2. Night time should be written as black background of text with white color text. No border.
Black Background
1. Day time should be written as white background with black as text color with no background. No border.
2. Night time should be written as white border around the white color text.
Handwritten Format:
1. Day time should be written as normal dark ink color.
2. Night time should be written as normal dark ink color with a border around it.
Second Ringtone December 14, 2008 No Comments
I guess I am still learning and trying to master music, I can only create small bits and pieces only in music yet so thats why name “Ringtone” because this music is practically not useful for anything else.
This was made with progression “1 3 4 2 1″.
I just chosen a random progression to begin with, I am still searching for some way to learn and understand progression much at depth in order to create good music.
Feel free to download and use it.
RIA – Why? Which One? How? December 13, 2008 9 Comments
RIA (Rich Internet Application) means faster means to develop light applications to fit in your business presentation and few quick interactive applications. With RIA you can not make a money tree and you can not become rich.
Target Applications:
- Frontend Applications
- Small Quick Demo Applications
- Graphical Analysis of MIS
- Marketing Presentations
- Quick Forms/Data Entry for Mass Audience
- Polls, Social Interaction Applications
- Thin Client Applications
With RIA you can generally make a thin client applications, which surely needs to interact with high poerful web server or any other form of server over internet. RIA replaces frontend for modern internet applications from traditional HTML/JS form processing websites.
WHY RIA?
Traditional web portal applications (ASP.NET/EJB..) takes too much of time to process every single request, as it does not use full potential of client side computer. Every decision of which button to be displayed, state of an application and user’s choices and preferences, everything is maintained on server and applications utilizes too much of bandwidth as well.
Thats why, RIA is simple step to differentiate user interface and business logic completely with implementations of standards like SOAP web services and REST apis.
All RIAs are compiled at development site, that means the final RIA is in form of an application, which will execute accurately as designed. However in traditional HTML+JS, if any part of HTML is not rendered properly or its coded wrongly, there is no way to detect until it is delivered to browser and some error has been encountered. Pre compilation on RIA, reduces time required to develop web application drastically.
WHICH RIA?
| Flex | Silverlight | JavaFX | XUL | |
|---|---|---|---|---|
| Vendor | Adobe | Microsoft | Sun Microsystems | Mozilla |
| Open Source | Yes (I am talking about FLEX not Flash) |
No | Yes | Yes |
| Support
Community Support is very bad when you need quick solution in an emergency. |
Paid Support & Community | Paid Support & Community | Community Support | Community Support |
| Dependency | Flash Player | Silverlight Player | Java Runtime + JavaFX Runtime | XUL Runtime |
| Availability
According to various statistics, the by default availability of dependent software on PCs. |
95% | 10% | 0%
Although few PCs and all MACs have Java Runtime, they still need something additional. |
30% as FireFox supports XUL Apps |
| Size of Runtime | 1MB | 4.5MB | 30MB | 4MB |
| Native Device Access | Camera, Mic and Speakers | Speakers | Speakers | None in Web App,
May be few in Desktop App |
| Audio Video Support | Widely used FLV and MP3 format, stable and its there since 2001 | WMV/WMA/WMA Pro | No | No |
| Converters for the Supported Video | FFMPEG and many other commercial vendors available | Paid Encoders | No | No |
| Documentation | SDK Documentation and Samples | MSDN but still very premature, (Reason, the learning curve is little higher) | JavaDocs but JavaFX is still new | Apache Documentation, very scattered, difficult to learn. |
| Syntax | XML + Action Script | XML + C# / JS / VB.NET | Totally New Syntax | XML + JS |
| Language Feature | Strictly Typed with “Object” being dynamic type | Strictly Typed,
Dynamic type to come in C# 4.0 |
Strictly Typed | Dynamic Typed |
| Binding Expressions
Flex introduced wonderful concept of auto updating expressions when properties or variables changes. |
Very Accurate | Accurate but lengthy code | Available | Better then JavaFX and Silverlight |
| Two Way Databinding |
Not Available, Coming up in Flex 4 | Available | - | Available |
| Binding Declaration | Simple Attribute | Extra Code in each bindable property | Extra code in each bindable property | Simple Attribute |
| Reflection | Available | Available | Available | Available |
| Code Size | Very Concise | Even simpler things like validator etc takes 6 lines, too big code size to maintain | Size is small, but very disorganized, difficult to read | Concise enough |
| Platform Availability | Windows, Mac, Linux | Windows Only | Windows, Mac, Linux | Windows, Mac, Linux |
| Stability | Very Stable | Pre Beta | Pre Beta | Stable Enough |
| Control Library | Rich set of Controls available, plus lots of free stuff available as well | Very basic controls, you have to spend money on other ISVs to get good controls | Good set of Controls | Almost everything is free, lacks good documentation though |
| Coders Availability
For project managers, how difficult it will be to find coders who will code. |
Easily Available as existing Flash, HTML, JS, ActionScript can code. | C# and Microsoft Technology programmers can code. | Java Programmers can code, but due to new syntax, its still difficult to get hands on it. | Very difficult as it requires too extra knowledge of mozilla architecture and various standards, which is not taught anywhere. |
| Commercial Training
Starting project is very easy, but ongoing maintanence and meeting deadlines requires excellent knowledge of technology, which you should not rely on community blogs, because time required to search any solution is costly. |
Excellent | Excellent | Training available | Where? |
| Threading Support | No | Limited | No | Limited |
| Themes/Skinning | Yes | Yes, but size of code is very big | No | Yes |
| WebService Integration | Yes | Yes | Yes but very frustrating | Yes |
| Upload/Download | The Best Feature in Flex | Yes | Yes | Yes |
| Installable on Desktop | Yes | No | Yes | Yes |
| Database Support (in desktop app only) | Sqlite | Not Applicable | JavaDB
Too heavy and too slow |
Sqlite |
| Auto Update on Desktop App | Yes | No | No | Yes |
| Present Since | 2001 | 2007 | 2007 | 2001 |
| IDE
Plugins are available under eclipse and netbeans etc type of editor, but problem is they are so premature, they dont support refractoring, analysis, debugging and lots of other facilities. |
Flex Builder | Visual Studio | Plugin | Plugin |
| IDE Cost | ||||
| IDE Refractoring | Yes | Yes | No | No |
| IDE Source Versioning | CVS
Good for Multiusers |
Source Safe (Single Developer only)/ TSS (too costly) | Plugin | Plugin |
| Drag and Drop Editor | Yes | Limited, because to script you need Visual Studio and to design you need Blend (Other paid software) | No | No |
| Code Intellisense (Auto Complete) | Yes | Yes | ||
| Project Management | Yes | Yes | ||
| Library Management
Creating and importing shared code in the form of libraries. |
Yes | Yes | ||
| Component Development | Very Simple | Quite Complex as it is divided in User/Custom controls categories. | Available | Simple |
| The Result |
Leader of RIA | Flex Follower | The Last | Linux Love |
Important Note:
Silverlight claims to be platform independent, but reality is, Microsoft no longer provides any more upgrades of Silverlight version for any other operating system other then Windows. And Linux was already not officially supported by Microsoft.
Advantages of RIA
- Reduce Development time
As compared with traditional web application, since RIAs are pre compiled, errors due to syntax, wrong spellings can be detected earlier at time of desiging. - Load First, Run Throughout
RIAs load entire application (Except XUL) in the beginning, instead of HTML+JS, which loads as things proceed. This means, either application will load completely and work accurately even with slower bandwidth connection, or if some part didnt load, it will straightway display an error. So it works like transaction, either all or nothing. HTML+JS can behave unexpectedly in case of missing components. - Seperate Design and Development Processes
Flex and Sliverlight offers complete seperation of Development and Designing keeping integration simple, other platforms (earlier web ones) require too much time integrating designs and process. - Utilize Client Computing
Almost every computer has high powerful graphics capabilities, HTML/JS doesnt offer any great benefit over it. RIAs can completely explore native graphics capabilities and you get wide range of user interface functionality.
C# Optimizations Via Caching December 12, 2008 14 Comments
Being computer science expert, I can visualize the load on Processor when I write the code, and though its cumbersome sometime to write more code to perform optimized operation,but its real worth while to spend time to understand Caching in programming.
Static Caching Config Values
The configuration values that you probably store in some config file, or some xml, or some registry etc should be statically cached in any class. For example, you need to access "AppConnectionString" defined in web.config or app.config, if you use expression
WebConfigurationManager.ConnectionStrings["AppConnectionString"]
every time then it would be very costly as first it tries to get instance of config file, then the section and then once again the HashTable of probably NamedValueCollection type and so on. This all is very costly for any value that is stored in config file and which stays unchanged for months or even years. I would always access it in a static class like this.
private static string _AppConnectionString = null; public static string AppConnectionString { if(_AppConnectionString == null) { _AppConnectionString = WebConfigurationManager .ConnectionStrings["AppConnectionString"] .ConnectionString; } return _AppConnectionString; }
Property Cache in Local Variable
Consider following code
void DrawEffectRectangle(Rectangle r) { for(int i=50; i>=0;i--) { SetColor(i*5); Draw3dRect(r.Left - i, r.Top - i, r.Right + i, r.Bottom + i); } }
This method uses 4 properties, Left, Top, Right and Bottom, now consider following effective code which produces exactly same effect.
void DrawEffectRectangle(Rectangle r) { int left = r.Left; int top = r.Top; int bottom = r.Bottom; int right = r.Right; for(int i=50; i>=0;i--) { SetColor(i*5); Draw3dRect(left - i, top - i, right + i, bottom + i); } }
Now note, the calls to property evaluation has been reduced, lets assume one property access code takes 1ms then this code will execute 446ms times faster then the earlier code.
Note, you should use this technique carefully after examining that the value of these property evaluations are constant throughout the execution.
Cache Before Loop
Assuming following code,
for(int i=0;i<Results.Length;i++) { ProcessResult(Results[i]); }
Now here as well, expression i<Results.Length gets evaluated Results.Length times, assuming it to be an array. But consider the following code,
int len = Results.Length; for(int i=0;i<len;i++) { ProcessResult(Results[i]); }
Caching once again the Length in a local variable reduces Property Evaluation code.
QueryString Caching
Most of the time, we have habbit of using ‘Request.QueryString["SomeID"]‘ this is very bad if you keep on calling this way, you must cache this in beginning of Page processing that will significantly improve your Web Server Performance. I would use following way to initialize my QueryString based Page variables.
private T GetQueryStringValue<T>(string name, T def) { object val = Request.QueryString[name]; if(val == null) return def; return (T)Converter.ChangeType(typeof(T),val); } private long CustomerID = 0; private string Process = ""; private void Page_Load(object sender, EventArgs e) { CustomerID = GetQueryStringValue<long>("CustomerID", 0); Process = GetQueryStringValue<string>("Process", "Signup"); }
And then using the values of CustomerID and Process variables rather then accessing Request.QueryString object again and again. There are two advantages in it, first, you can avoid Request.QueryString calls, and second you can compare native type comparisons to evaluate your algorithm flow. And you can see yourself after decompiling Request object through Reflector, that each access of Request.QueryString and its indexer basically requires more then 20-80 steps to get final result. Sure processor has 3 GHz but that doesnt mean that 1000 requests can just waste so many cpu cycles and finally frustrating the end user who is waiting expecting some result !!
Session Variable Caching
I would also try to cache, session variable in local page class as defined following,
private long _SessionWebUserID = -1; private long SessionWebUserID{ get{ if(_SessionWebUserID == -1) { _SessionWebUserID = 0; object val = Session["WebUserID"]; if(val != null) { _SessionWebUserID = (long)val; } } return _SessionWebUserID; } }
Sure this method has additional _SessionWebUserID != -1 comparison everytime you access the property, but belive me, its far less costly then accessing Session NamedValueCollection again and again.
However the drawback is, if you cache session variable for longer period then its life in static variable, if it changes outside in session, you will never know. Thats why I always keep it as instance property instead of static, so I assume that atleast for this instance of page, the session value is constant.
Avoid Property of Property Style
Consider following code,
string url = HttpContext.Current.Request.Url; string method = HttpContext.Current.Request.Method;
Both method has HttpContext.Current.Request as common code, and it actually has 2 Property Evaluation codes. Considering simple property evaluation execution time is 1ms, above code finishes in 6ms.
Ideally such code should be written as,
HttpRequest request = HttpContext.Current.Request; string url = request.Url; string method = request.Method;
Now this rewritten code finishes in 4ms, as first statement executes two property evaluation code to get final useful HttpRequest object.
Caching Method Results
Sure all of above methods even apply to method results too, as Property evaluation is just an internal get_Property method.
Result
Ok fine, I do the caching but how it improves performance? The answer is quite simple, each of above discussed methods requires numerous Property evaluation, Hashtable eveluation code, in order to read certain values. Now accessing local stack variable or static variable is many times faster then accessing property as it is a new method to access some other variable or some calculated variable. The indexed or hashed properties take even more time as the search is dependent upon the number of items present in the list or dictionary. Each such operation may execute few millsecond faster then before, but the overall performance increases with many concurrent execution. Not only CPU cycles but memory usage also can be improved as less method calls, less stack in use and less overhead on memory.
Oh such big lecture just for avoiding Property Evaluations? Well yes, remember Property Evaluation code is nothing but a simple method execution for CPU. And inside the .NET CLR environment, CPU needs to do a lot before an actual code is executed. Please note, this is assumed hypothetical Call sequence, the actual .NET CLR call sequence can be much more complex.
- Access target object (in which property exists)
- Access internal "Get" method handle for this target object’s type
- Allocate the Stack
- Do some book keeping, note the pointer values for tracking Exception StackTrace
- Setup local variables if any
- Move to the pointer of first instruction
- Evaluate expressions and actual code (for NamedValueCollection this could be quite long)
- Push result on stack
- Finish the Call
- Pop the result
- Unwind stack and do some book keeping to unwind Exception StackTrace
So, you can see, CPU needs to do a lot just before it can give you property evaluation result. And in case of Cached value in local variable, this can simply reduce in one or two instructions for subsequent frequent access.
Memory Usage
Using more such cached variables doesnt increase memory overhead? Well significantly not, because you are not going to have million such variables in one single threaded execution, most of these variables will be reused from time to time. Each local cached variable in method execution is on stack, and it only takes one space unit, however executing actual property again and again will even require more stack usage.
This isn’t same as External Caching
Sure web servers are written with great deal of effort and do provide good caching mechanism. Even ASP.NET has various caching methods, but those caching things are for very generalized purpose, the methods I am detecting here is not supposed to be misunderstood with the page, control caching. Because even other caching methods requires at least first time complete processing in order to get the results. Also these are pure processor level execution improvements, it has nothing to do with where your application is executing, it can be your web server code or your mobile app code or even database assembly code.
First Ringtone December 7, 2008 No Comments
However I will get better name of the songs when I know for what I created them and how I created them, right now I guess number just differentiates it from other files.
This was created using Fruity Loops version 7 and it basically contains Blues Progression with Glass Bell leads.









