Should I cache instances of frequently accessed classes - asp.net

New to .net and was wondering if there is a performance gain to keeping an instance of, for example a DAL object in scope?
Coming from the Coldfusion world I would instanciate a component and store it in the application scope so that every time my code needed to use that component it would not have to be instanciated over and over again effecting performance.
Is there any benefit to doing this in ASP.Net apps?

Unless you are actually experiencing a performance problem, than you need not worry yourself with optimizations like this.
Solve the business problems first, and use good design. As long as you have a decent abstraction layer for your data access code, then you can always implement a caching solution later down the road if it becomes a problem.
Remember that any caching solution increases complexity dramatically.

NO. In the multi-tier world of .asp this would be considered a case of "premature optimization". Once a sites suite of stubs, scripts and programs has scaled up and been running for a few months then you can look at logs and traces to see what might be cached, spawned or rewritten to improve performance. And as the infamous Jeff Atwood says "Most code optimizations for web servers will benifit from money being spent on new and improved hardware rather than tweaking code for hours and hours"

Yes indeed you can and probably should. Oftentimes the storage for this is in the Session; you store data that you want for the user.
If it's a global thing, you may load it in the Application_Start event and place it somewhere, possibly the HttpCache.
And just a note, some people use "Premature Optimisation" to avoid optimising at all; this is nonsense. It is reasonable to cache in this case.

It is very important to do the cost benefit analysis before caching any object, one must consider all the factors like
Performance advantage
Frequency of use
Hardware
Scalability
Maintainability
Time available for delivery (one of the most important factor)
Finally, it is always useful to cache object which are very costly to create or you are using very frequently i.e. Tables's Data (From DB) or xml data

Does the class you are considering this for have state? If not, (and DAL classes often do not have state, or do not need state), then you should make it's methods static, and then you don't need to instantiate it at all. If the only state it holds is a connection string, you can also make that property field a static property field, and avoid the requirement of instantiating it that way.
Otherwise, take a look at the design pattern called Flyweight

Related

static in a web application

I want to generate a very short Unique ID, in my web app, that can be used to handle sessions. Sessions, as in users connecting to eachother's session, with this ID.
But how can I keep track of these IDs? Basically, I want to generate a short ID, check if it is already in use, and create a new if it is.
Could I simply have a static class, that has a collection of these IDs? Are there other smarter, better ways to do this?
I would like to avoid using a database for this, if possible.
Generally, static variables, apart from the places may be declared, will stay alive during application lifetime. An application lifetime ended after processing the last request and a specific time (configurable in web.config) as idle. As a result, you can define your variable to store Short-IDS whenever you are convenient.
However, there are a number of tools and well-known third-parties which are candidate to choose. MemCache is one of the major facilities which deserve your notice as it is been used widely in giant applications such as Facebook and others.
Based on how you want to arrange your software architecture you may prefer your own written facilities or use third-parties. Most considerable advantage of the third-parties is the fact that they are industry-standard and well-tested in different situations which has taken best practices while writing your own functions give that power to you to write minimum codes with better and more desirable responses as well as ability to debug which can not be ignored in such situations.

Can ASP.NET performance be improved with modules/static classes?

Can using Modules or Shared/Static references to the BLL/DAL improve the performance of an ASP.NET website?
I am working of a site that consists of two projects, one the website, the other a VB.NET class library which acts as a combination of DAL and BLL.
The library is used to communicate with databases and sometimes transform/validate the data going into/coming from the DBs.
Currently each page on the site that needs db access (vast majority) will create an instance of the relevant class in the library to access specific tables.
As I understand it this leads to a class from the library being instantiated and garbage collected for each request, with the possibility of multiple concurrent instances if multiple users view the same page.
If I converted the classes to modules (shared/static class) would performance increase and memory be saved as only one instance of each module exists at a time and a new instance is not having to be created for each request?
(if so, does anyone know if having TableAdapters as global variables in the modules would cause problems due to threading?)
Alternatively would making the references to the Library class it the ASP.NET page have the same effect? (except I would have to re-write a lot less)
I'm no expert, but think that the absence of examples of this static class / session object model in books and online is indicative of it being a bad idea.
I inherited a Linq-To-Sql application where the db contexts were static, and after n requests the whole thing just fell apart. The standard model for L2Sql is the Unit-of-Work pattern (define a task or set of tasks - do them and close). Let the framework worry about connection pooling and efficient GC.
Are you just trying to be efficient or do you have performance issues? If the latter it's usually more effective to look at caching or improving query efficiency (use stored procedures, root out queries in loops) than looking at object instantiation.
Statics don't play well with unit tests either (another reason why they have dropped out of fashion).
instances are only a problem if they are not collected by the CG (a memory leak). Instances are more flexible than static as well because you can configure the instance to the specific context you are using.
When an application has poor performance or memory problems its usually a sign that
instances are not properly released (IDisposable)
the amount of data retrieved is too big (not paging large sets of data)
a large number of queries are executed (select n+1, or just a lot of queries)
poorly constructed sql statements (missing indexes, FK, too many joins, etc)
too many remote calls (either to other servers, or disk)
These are first things I would check. then start looking at the number of instantiated objects. Chances are that correcting the above mentioned list will solve most performance bottlenecks.
Can using Modules or Shared/Static references to the BLL/DAL improve
the performance of an ASP.NET website?
It's possible, but it depends heavily on how you use your data. One tradeoff in using a single shared instance of an object instead of one per request is that you will need to apply locking unless the objects are strictly read-only, and locking can both slow things down and complicate your code (not to mention being a common source of bugs).
However, if each object is going to contain the exact same data, then the tradeoff may be worth it -- even more so if it can save a DB round-trip.
You might consider using either a Singleton or a small number of parameterized objects rather than a static, though -- and use caching to manage them. That would give you the flexibility to let go of objects that you no longer need, which is harder to do when you're dealing with statics.

What cache strategy do I need in this case ?

I have what I consider to be a fairly simple application. A service returns some data based on another piece of data. A simple example, given a state name, the service returns the capital city.
All the data resides in a SQL Server 2008 database. The majority of this "static" data will rarely change. It will occassionally need to be updated and, when it does, I have no problem restarting the application to refresh the cache, if implemented.
Some data, which is more "dynamic", will be kept in the same database. This data includes contacts, statistics, etc. and will change more frequently (anywhere from hourly to daily to weekly). This data will be linked to the static data above via foreign keys (just like a SQL JOIN).
My question is, what exactly am I trying to implement here ? and how do I get started doing it ? I know the static data will be cached but I don't know where to start with that. I tried searching but came up with so much stuff and I'm not sure where to start. Recommendations for tutorials would also be appreciated.
You don't need to cache anything until you have a performance problem. Until you have a noticeable problem and have measured your application tiers to determine your database is in fact a bottleneck, which it rarely is, then start looking into caching data. It is always a tradeoff, memory vs CPU vs real time data availability. There is no reason to make your application more complicated than it needs to be just because.
An extremely simple 'win' here (I assume you're using WCF here) would be to use the declarative attribute-based caching mechanism built into the framework. It's easy to set up and manage, but you need to analyze your usage scenarios to make sure it's applied at the right locations to really benefit from it. This article is a good starting point.
Beyond that, I'd recommend looking into one of the many WCF books that deal with higher-level concepts like caching and try to figure out if their implementation patterns are applicable to your design.

WebApplication Architecture - Advice on keeping HTTPContext in the Presentation layer

The majority of the Application Architecture advice seems to advise strongly that only Presentation Layer should have access to HTTPContext (to promote loose coupling, decrease dependencies, increase testability etc).
So, how do people deal with Caching and Session? Very specific DataAccess and Business Logic knowledge is required to determine what items need caching to best benefit application performance. However, and an ASP.Net web application, access to these is provided via the HTTPContext.
One option would be to create a CacheFactory and a SessionFactory, and an ICache and ISession interface - and then somehow use DI principle to pass and ISession and ICache to each method in the BLL and subsequently DA Layer that needs it.
Is this really what developers end up doing? Is there another, easier, way to deal with this?
Thanks for any advice.
Personally, if I'm developing for ASP.NET (web) only, and I know the class libraries are only going to target the web, I have no issues referencing System.Web or any other assembly as needed. Sometimes practicality should come first.
On the other hand if you know, or are unsure if the BLL, DAL or other layers may be reused in a client-server or other environment, you may need to look at using a more flexible approach such as a session handler interface, etc.
The main thing is you clearly understand what best practice recommends. At that point you can make rational decisions about what should apply to each project or situation. It won't always fit like a glove.
In my experience caching is done ata certain layer - and what you're caching applies within the scope of that layer, so:
You might cache data in the DAL so that the DAL returns it from memory and not by hitting the DB again; so here we're caching "raw" data at the data level.
The BL might cache similar data (say POCO's) - in other words "logical" data that has had BL applied to it; so here we're caching BL data in the BL level.
Your UI might cache (you guessed it) information that is built at the UI layer - liek a presentation of data as a webpage, XML, etc.
When you look at caching, as the architect / designer of the system you'll make decisions about what things are worth caching, generally this will be driven by a need to balance:
Performance needs to hit a specific target.
What time (and cost) options you have.
Assuming we're caching to increase performance, you'll want to analyse your system and identify the bottlenecks that need to be removed or avoided - the first pass of this analysis should at least identify which layer to focus on first.
Another thing to consider is that the more you can cache closer to the consumer - the less overall processing there is that needs to occur; in otherwords, if you can cache at the UI layer then the BL and DAL layers won't even get a look-in (you won't need to add caching there).
At this point I want to ask you what exactly it is that you're trying to achieve.
While everything I've said is true (as far as I am aware) it's all based on the assumption that we're delivering "vertical" slices of the systems functionality (like "creating an invoice", "adding a product" etc); there's another model you can apply - the cross-cutting concerns model.
Think about something like logging - every part of you system (UI / BL / DAL) should be able to log system events; my favourite tool for this is the MS Enterprise Libraries (MSEntLibs). When I work with them I consider them to be a "black-box" - a self contained unit. I (by choice) have no idea how they are architected - the thing that is important is that they are isolated and have dependencies which are relativly easy to manage.
The MSEntLibs can log to a database, but if I call an MSEntLibs logging method (to log to the DB) direct from my UI (and skipping over my BL) I don't care.
So depending on what you're trying to do the right anmswer will either be:
Simply identifying what needs to be cached at letting the appropriate layer handle it.
You don't need to try using DI to pass stuff to you BL at all - a cross-cutting black-box component might be appropriate?

What's the best approach with global variables in ASP.Net applications?

For my global variables and data I find myself in a dilema as to whether to use HttpApplicationState or Static variables - What's the best approach?
This document states that one should use static variables over httpapplicationstate:
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607
However, one thing I like about HttpApplicationState (and System.Web.Caching.Cache), is that one can easily enumerate the entries and select which items to remove (I've created a global CacheManager.axd for this purpose), whereas I don't believe there's an easy way with Static variables (and even then it's not clear what to do to "re-initialise" them), without recycling the app pool.
Any suggestions on a neat general-purpose way to handle and manage global objects?
Thanks, Mark.
Your instincts are correct. Use System.Web.Caching. The built-in cache management takes care of all the heavy lifting with respect to memory allocation and expiring stale or low priority objects.
Make sure to use a naming convention, for your cache keys, that makes sense down the road. If you start relying heavily on caching, you'll need to be able to target/filter different cache keys by name.
As a general practice, it's good to try to avoid global state in web applications when possible. ASP.NET is a multithreaded environment where multiple requests can get serviced in parallel. Unless your global state is immutable (readonly), you will have to deal with the challenges managing shared mutable state.
If your shared state is immutable, and you don't need to enumerate it, then I see no problem with static variables.
If your shared state is volatile/mutable, then you probably want to create an abstraction on top of whichever underlyig mechanism you choose to store the data to ensure that access and modification of that shared state is consistent and complies with the expectations of the code that consumes it. I would probably use the system cache in such a design as well, just to be able to leverage the expiration and dependency features built in to the caching service (if necessary).

Resources