Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
The default cache size is 300, according to the code. Your snippet won't tell you anything useful about the size of the cache. When the locmem cache is full, a subsequent set will cause it to evict items based solely on the modulus of their key's position in the dict, which is unpredictable. There is no attempt to evict based on LRU, FIFO or any other algorithm. This is yet another reason not to use this backend n production.
What is the default size of the local memory cache for Django. https://docs.djangoproject.com/en/1.8/ref/settings/ does not mention any. https://docs.djangoproject.com/en/1.8/topics/cache/#cache-arguments says it is 300, but the following code always returns a different value: for i in range(0, 10000): cache.set(i, i) first = cache.get(0) if first is None: print i break I have seen values ranging from 150ish to 1500ish. Thanks!
Django localmem size
Serializing an object into a string and storing it as is in Redis is certainly one way of doing that. Another way would be to model your custom object using Redis data structures. Most often, this is done using the Hash data type but, depending on the object's properties and your read/write requirements, you may want/need to use other types. There are also helper libraries that can do this for you almost automagically - they usually go by the acronym ORM (Object Redis Mapper) or a variation of it. I'm not too familiar with the .NET scene, but here's a possible direction that you can research: https://github.com/ServiceStack/ServiceStack.OrmLite
In redis cache we can store data into key value pair , how do I store full object data ? I want to store customer information inredis cache I tried google and found this following but I wonder How to use it can any one elaborate more ? public bool Add<T>(string key, T value, DateTimeOffset expiresAt) where T : class { var serializedObject = JsonConvert.SerializeObject(value); var expiration = expiresAt.Subtract(DateTimeOffset.Now); return database.StringSet(key, serializedObject, expiration); } public T Get<T>(string key) where T : class { var serializedObject = database.StringGet(key); return JsonConvert.DeserializeObject<T>(serializedObject); }
How do I store customer class object data into Redis Cache?
The problem is at real path cache level. It caches the PHP file with the symlink path. What you need to do is provide the real document path. You need to add these 2 lines in your config file fastcgi_param DOCUMENT_ROOT $realpath_root; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; The important part is $realpath_root. From the documentation: $realpath_root an absolute pathname corresponding to the root or alias directive’s value for the current request, with all symbolic links resolved to real paths Meaning $realpath_root solves all symlinks to their real path. This is the important part. So your location ~ \.php$ would become location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param DOCUMENT_ROOT $realpath_root; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; } Make sure the include fastcgi_params if present does not overwrite the 2 directives you just added.
I've got a problem with deploying my application. I have a PHP application and I deploy my application with Capistrano to my server. Capistrano makes a new release folder with the latest version of my application and my current folder symlinks to the that release. That works fine, it really links the latest release. But when I go the the URL of my website nothing changes, the files are from the old release folder even when the symlink links to the current folder (latest release). Does Nginx cache all my files? Or does it cache my symlinks, I have no idea. Folder structure: current (symlink new release) releases new release old release Vhost: server { listen 443; server_name servname.com; root /apps/application/production/current/public; }
Nginx vhost cache symlink
Play's default cache implementation uses EhCache, which is an in-memory cache. Everything that's cached (should be) serialized as bytes, and stored in memory somewhere. There is no encryption as far as I know. So no, there are no files you can access. And because it's an in-memory cache, its gone as soon as you shut down or restart the server. As pointed out by @RichDougherty, you can configure EhCache to cache to disk, rather than memory. I dropped this ehcache.xml into my conf directory: <ehcache> <diskStore path="/home/mz/temp"/> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> </ehcache> ..Which spits out a binary play.data file into that directory. I don't quite understand why you'd want to cache to disk, unless you're really strapped for memory. Disk caching would not be very efficient for a local cache, and would not work in a distributed environment. Instead of an in-memory or disk cache, you can use another cache plugin like memcached or redis. If you need to access the cache from outside the application in those instances, then you can do so with another implementation. For instance, if you use redis, you can use redis-cli.
I am building Java application which uses Play Framework and it is crucial for me to access cached files. I am looking for a place where Play Framework's cache resides. Is that somewhere on disk, and if yes, where? Can I access files from it (e.g. from windows explorer) somehow or it is deliberately hidden from users (or maybe encrypted)?
Where is play framework cache stored?
5 I wonder how you imagine transferring an Object over the wire without serializing it? Take a deep and thorough read on the documentation here. And more specifically, the Working with .NET Objects part. The latter already gives also the answer to your second question. Share Improve this answer Follow answered Mar 10, 2015 at 9:34 astaykovastaykov 30.8k33 gold badges7171 silver badges8686 bronze badges 2 Thanks for links. Is there a way to find out what's been stored in Cache/Session? Basically I would like to find out whether my object is stored in cache or not. – Nil Pun Mar 10, 2015 at 9:50 when you read carefully through the article you will get answers to all your questions! – astaykov Mar 10, 2015 at 11:42 Add a comment  | 
I'm planning to use the Azure redis for session state and caching purpose. In the past I've used enterprise library and azure dedicated cache which requires [Serializable] attribute for all the objects (complex objects) that needs to be stored. Can someone please help me understand what are the requirement for object to be stored as session or cache using azure redis? Also is there any pattern ask Cache to give back given object. e.g. if I ask for employee object the cache should give me that.
does azure redis cache/session requires Serializable attribute
The script is cached and the browser does not pull the new version from the server. We need to edit the header of the requests for the files in the /workers folder, using the following code server-side (I wrapped it in a package with api.use('webapp')): WebApp.rawConnectHandlers.use('/workers', function(req, res, next) { res.setHeader('cache-control', 'must-revalidate'); next(); }); Using WebApp.connectHandlers did not work, the callback was never called, so I used rawConnectHandlers instead. I am not 100% sure it is the best way to go, but it works.
In my project there is a public folder and a script inside it: public/worker.js, which contains a piece of code: alert('foo'); I call this script using a Worker: new Worker('worker.js'); I launch Meteor and connect to my app. foo is alerted. If I change the public/worker.js code to anything else: alert('bar'); The server refreshes the clients, the client refreshes the page but won't get the new code, instead using the old one (alerting foo instead of the new shiny bar). Clearing the cache then refreshing fixes the issue. CTRL+F5 does not fix this cache issue, it does not seem to work for this kind of script call (at least not on the version of Firefox I tested it with). Why is this happening, exactly? How can I prevent it?
Why won't the client receive new versions of this script in the public folder?
5 No, cache lines are one size (eg: 16, 32, or 64bytes), virtual pages are another independent size (often 4K). Reading an entire 4K page into the cache would be too slow and make the cache ineffective for most use cases so CPUs use smaller cache lines. Share Improve this answer Follow answered Jan 1, 2015 at 16:34 Stephane HockenhullStephane Hockenhull 18555 bronze badges 3 why would I move 4K from the disk to memory when needed, while all size I need in the cache is 64bytes. I don't understand what would I do with the rest of the 4k I didn't use. – Yousef Jan 1, 2015 at 17:27 1 Because you can only mark entire pages as accessible or inaccessible. The reason why pages are much larger is due to the size of the page-table that would be required for smaller pages. It takes over 4MB to map 4GB of 4KB pages, if pages were 64bytes it would take over 256MB of page table to map the entire 4GB of ram on a 32bit CPU. There's also a high overhead for reading 1 sector from HDD while reading multiple consecutive sectors has much lower overhead after the first, making it efficient to read, say, 4KB at once. – Stephane Hockenhull Jan 2, 2015 at 5:06 What if my block size is 128MB and I want to do 64KB pages? does that even make sense? – user1870400 Oct 2, 2019 at 20:27 Add a comment  | 
We all know in address translation from virtual address to physical address, the lower bits are used as page offset so they are not translated. Instead they stay the same. This means that the page size in virtual memory is the same as the physical memory. We also know that when moving a block from memory into the cache using modulo method, the size of the block in both sides is the same. My question is, does this mean that the page size in virtual memory should be the same as the block size in cache.
Page size and block size
If it's possible to change isExpired: V => Boolean to timeToLive: V => Duration, then you can use def refresh(k: String): Future[V] = readV(k) andThen { case Success(v) => Cache.set(k, Future.successful(v), timeToLive(v)) } def get(k: String): Future[V] = Cache.getOrElse(k)(refresh(k)) To control concurrency, I like the actor model: object Lookup { case class Get(key: String) class LookupActor extends Actor { def receive = { case Get(key) => Cache.get(key) match { case Some(v) => sender ! v case None => val v = Await.result(readV(k), timeout) Cache.set(key, v, timeToLive(v)) sender ! v } } } } Using actors, it'd be nice if we had a readV that provides the result synchronously, since the actor model provides the concurrency (and control). Client-side, it's: val futureV = lookupActor ? Lookup.Get(key) mapTo[V]
Given following functions val readV : String => Future[V] val isExpired: V => Boolean How to memorize the result of readV until it isExpiredby using play cache(or something else) Here is how I did: def getCached(k: String) = Cache.getAs[Future[V]](k) def getOrRefresh(k: String) = getCached(k).getOrElse { this.synchronized { getCached(k).getOrElse { val vFut = readV(k) Cache.set(k, vFut) vFut } } } def get(k: String) = getOrRefresh(k).flatMap { case v if !isExpired(v) => Future.successful(v) case _ => Cache.remove(k) getOrRefresh(k) } This is too complicated to ensure correctness Is there any simpler solution to do this.
play-cache -- memorize an Future with expiration which depends on the value of future
From prepare documentation: Prepared statements only last for the duration of the current database session. When the session ends, the prepared statement is forgotten, so it must be recreated before being used again. So the statement and it's plan does not survive closing the connection and it is not cached.
From my understanding, Postgres will cache prepared statements automatically. If I do the following in pseudo code: connect() prepare("statement1", SQL1, params1) exec_prepared("statement1") close() Then later I do the following again connect() prepare("statement1", SQL2, params2) exec_prepared("statement1") close() How will Postgres handle these two prepared statements from a caching point of view?
Are PostgreSQL prepared statements cached by the statement name?
From a Varnish/Browser/End-user perspective they are both optional and can be removed.
We have just deployed several varnish instances in production and I'm wondering whether is it ok to unset the Via: and X-Varnish: headers. As far as I read Via is only an info header, while X-Varnish is for debugging, but I didn't find info about whether they're optional or necessary. So is it safe to removed them like this? sub vcl_deliver { unset resp.http.Via; unset resp.http.X-Varnish; }
Varnish Via and X-Varnish headers: are they needed in production?
5 Use the @DirtiesContext annotation, add this at the class level. It will then refresh the spring application context after the test class has executed. Documentation: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html Share Improve this answer Follow answered Sep 9, 2014 at 9:32 cowlscowls 24.2k88 gold badges4949 silver badges7878 bronze badges 4 thanks, but that doesn't seem to do the work. It's clear that ServiceTest1 is the problem, but I'm not sure where is the conflict. Even when I execute ServiceTest2 alone it fails. – tomper Sep 9, 2014 at 10:05 if ServiceTest2 doesn't work on its own then changing ServiceTest1 Wont fix the problem. You need to post more of ServiceTest2 plus the spring xml file – cowls Sep 9, 2014 at 10:12 when I remove the specific Context configuration from ServiceTest1 than everything works fine. – tomper Sep 9, 2014 at 10:18 Hmm ok, you must not be executing Service2 alone properly then. Will still need to see more of the code/config – cowls Sep 9, 2014 at 10:26 Add a comment  | 
My code has many integration tests classes - ServiceTest1, ServiceTest2 ... , ServiceTestN. All tests are executed with spring using the same test context (MyAppContext.xml). As shown in the snippet below, ServiceTest1 test context requires one of its beans to be overridden, and that change is relevant ONLY for ServiceTest1. When executed, ServiceTest1 works as expected. However, when executing the other tests (e.g. ServiceTest2 in the snippet) it fails with spring initialization errors, since spring is caching MyAppContext.xml test context, and ServiceTest1 test context manipulation is conflicting with the other tests. I'm looking for a way to avoid caching of ServiceTest20 test context (such as making its caching key unique, based on @ContextConfiguration). Note that fully disabling caching is not a wanted solution. Any ideas? ServiceTest21 Thanks! EDIT: Spring initialization errors are: java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:/WEB-INF/applicationContext-security] Offending resource: URL [file:/path/to/MyAppContext.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate detected. Offending resource: class path resource [WEB-INF/applicationContext-security.xml]
Spring & JUnit | How to disable spring test context caching for a specific test class?
4 Using in-proc or out-proc cache is purely application dependent. Inproc cache stores data in current application’s process memory which makes cached data access very fast however cached data is accessible only to the local application. This works fine if you have only one application server or if every application server is using a different data set. Even so, if the application server goes down, the cached data will be lost. However if your multiple application server using same set of data, Inproc cache is not the best solution. Since, in that case, every application would be loading the same data set hence limiting the usefulness of using cache. Moreover, for session state caching, it will leave you with the only option of using sticky-sessions which, in turn, would limit load balancing. On the other hand, distributed caching will add an extra network cost of getting data from another server, but it would give you an advantage of sharing the same data set with all other applications. Not only that but also, the data would remain cached even if the application server goes down. You can also use a hybrid solution of both Inproc and OutProc caching, like one provided by NCache, where you can have a distributed clustered cache (containing all cached data) and a local inproc cache (containing subset of data, frequently used by that application server). This will give you advantages of both caching techniques. Since you are re-writing your application, I will recommend you to try NCache. It provides both in-proc and out-proc solutions. You can write your application only once, test it with both solutions and go with the one which suits you best. Share Improve this answer Follow answered Sep 24, 2014 at 19:14 Sameer ShahSameer Shah 1,08377 silver badges1212 bronze badges Add a comment  | 
I'm looking into Redis and alternatives because we are going to switch to writing our applications distributed. My thought was that we need distributed caching such as Redis to ensure that we have a consistent cache everywhere. My senior colleague does not agree and says that we should just use selective InProc caching, where some data is cached in the machine's memory when it's requested. He also said that Redis will be much slower than caching the data InProc. He agrees that we should store Session state in a distributed cache because that needs to be consistent. What is the best place to keep a cache? InProc or distributed?
ASP.NET InProc caching vs distributed cache
2 You should check Varnish hits with help of Varnishstat. You can also put below code which you can check in browser if it got served from Varnish cache or backend. sub vcl_deliver { if (obj.hits > 0) { set resp.http.X-Cache = "HIT ("+obj.hits+")"; } else { set resp.http.X-Cache = "MISS"; # set resp.http.X-Cache-Hash = obj.http.hash; } return (deliver); } Share Improve this answer Follow answered Aug 5, 2014 at 6:49 KNOWARTHKNOWARTH 91277 silver badges1515 bronze badges 1 Thanks for hint. I've found X-Cache - MISS. How would I fix it? Would you please suggest me any clue? – Ankit Aug 8, 2014 at 7:46 Add a comment  | 
I'm newbie to Varnish Cache. I've installed Varnish 4 ( latest version) on Cent OS server successfully and configured perfectly. I'm also getting X-Varnish, Via 1.1 varnish - v4 in Response header. I've found everything working perfectly. If I stop varnish, website stops which seems correct. My question is, eventhough varnish is configured correctly I'm not having enough speed. I thought, I'm not getting varnish cache result, it looks server always called backend server to get results. Normally, without varnish it takes 3-4 seconds to get results. After installing varnish, It takes same amount of time. Resonse header Accept-Ranges bytes Age 0 Cache-Controlno-store, no-cache, must-revalidate, post-check=0, pre-check=0 Connectionkeep-alive Content-EncodinggzipContent-Typetext/html; charset=UTF-8DateFri, 01 Aug 2014 14:08:51 GMTExpiresThu, 19 Nov 1981 08:52:00 GMTPragmano-cacheServerApache/2.2.15 (CentOS)Set-Cookiefrontend=rfdi8hd6kq136puafk93lm0ra7; expires=Fri, 01-Aug-2014 15:08:51 GMT; path=/; domain=www.usapooldirect.com; httponlyTransfer-EncodingchunkedVaryAccept-Encoding,User-Agent Via 1.1 varnish-v4 X-Powered-By PHP/5.3.3X-Varnish Request Header Accepttext/html, application/xhtml+xml, application/xml;q=0.9 ,/;q=0.8Accept-Encodinggzip, deflateAccept-Languageen-US,en;q=0.5Connectionkeep-aliveCookiefrontend=rfdi8hd6kq136puafk93lm0ra7; external_no_cache=1; adminhtml=pt3bt6t30m4vtqdsm1ldv716v7Hostwww.usapooldirect.com Refererhttp://www.usapooldirect.com/User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Thank you, Ankit
Varnish with Magento 1.8.1 Community editon not getting cache results
5 You can still using fragment caching for your static pages, although the benefits are obviously more visible with dynamic / DB-driven pages. It's worth considering doing this should you have a lot of partial being rendered or costly view logic. Just wrap your page's template with: # about_us.html.erb <% cache 'about_us' do %> ... <% end %> the first time you hit the page in an environment where config.action_controller.perform_caching = true, it'll generate the fragment (which in this case is your whole page), and it'll serve that the next time you reload it. The cache digest will be invalidated when the template is changed: The template digest that's added to the cache key is computed by taking an md5 of the contents of the entire template file. This ensures that your caches will automatically expire when you change the template file. http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html Share Improve this answer Follow edited Jun 23, 2014 at 15:23 answered Jun 23, 2014 at 15:18 tirdadctirdadc 4,64333 gold badges3939 silver badges4747 bronze badges Add a comment  | 
In order to boost the performance of my Rails 4.0.2 app, I would like to cache the output of some of my static pages: class PagesController < ApplicationController def home end def about_us end def contact end end In the Rails Guide on Caching it says that "Page Caching has been removed from Rails 4" and moved into a gem. In the gem description it says, however, that it will be maintained only until Rails 4.1. Some other observers also advise against using Page Caching and endorse Russian doll caching instead. So what's the best way to cache a bunch of static pages that will never actually hit the database and only ever change (slightly) if a user signs in? Thanks for any suggestions.
What's the best way to cache static pages in Rails 4?
I would suggest to use the build in JSF resource library mechanism, which supports versioning of resources. Since the clients caches will load a given resource when its' path changes. This way you can change the version number of your resoures and urge the client to reload them, without having to deal with any cache ageing strategies. There are several good write-ups about this topic here on SO What is the JSF resource library for and how should it be used? JSF resource versioning JSF2 Static resource caching
I am developing an application using JSF2.0/Primefaces 4.0 and JBoss 7. The problem is that every time i make a new deployment (using .war), all of the users have to clean their browser cache to see the changes(mainly with images positioning). I know that browsers save the content of the page to make it run faster, but i also know that there is a way to control the HTTP param cache-control to make it re-validate the page. And the question is: How to make the client browser recognize that there is a new deployment and clean the stored cache? Of course, using JBoss 7. Also, i don't want to re-validate the cache in every access, only when there is a new deployment. Is that possible?
How to clean cache after a new deployment?
This sounds like a fine thing to store in a share cache, like memcache or redis (or, yes, even an SQL database-backed cache). You should read https://docs.djangoproject.com/en/dev/topics/cache/; this can explain how you can store the result of your HTTP call under a cache key and then retrieve it. The caching works the same regardless of what backend (memcache, redis, local memory, SQL DB) you use, so you can test this out with the local-memory cache or DB cache and, if you like it, move to a better solution like memcache.
Suppose I need to build a web application where each client will be simulating their trading strategy using historical stock data. The data will be provided by a 3rd party vendor over the internet: for example, fetching historical data for a single stock based on stock ticker through HTTP call. Also, I am planning to use Django as a back-end framework. Here is my question: I would like to be able to prefetch and cache the data on the server side, so that each client's request would not need to do an HTTP call again, but get it from the shared resource. I guess, storing it in database, like SQL could be one solution. However, is there a way to use memory shared between clients in Django on the backend side? Any pointer or suggestion would be very helpful. Thanks.
Caching data on backend side with Django (scalable applications)
If the future is failed, then the value will be removed from the cache: https://github.com/spray/spray/blob/master/spray-caching/src/main/scala/spray/caching/LruCache.scala#L79 So this should do it: cache(key) { server.one[X](...).map(_.get) }
I have got a db-access I would like to cache in my akka/spray-application. The db returns a Future[Option[X]]. I set up a lruCache and wrapped it araound my db-access. What I would like to achieve is, to cache the Option only, if it is Some(X) and not, if it is None. In the latter case the data should be retrieved from the db again. Alternativly I could fail the future if this would help... So far I remove the Option from the cache again via map and recover if it is None or the future failed: cache(key) { server.one[X](...) }.map { case Some(x) => Some(x) case None => { cache.remove(key) None } }.recover { case x => userCache.remove(key) } But this is very ugly, not to mention side-effects in the map, etc... Thank you in advance, Jens
spray-cache: cache only when not None
You should change your internets, since they give you wrong advices. Just remove all add_header lines from your location (as well as surplus brake): location ~ ^/assets/.*-([^.]+)\.(js|css)$ { gzip_static on; # there's also a .gz of the asset expires max; } and read the docs from the true Internet: http://nginx.org/r/expires and https://www.rfc-editor.org/rfc/rfc2616
I'm trying to tell nginx to cache some of my assets (js, css) forever, or at least for a very long time. The idea is that once an asset bundle is compiled and published with an /assets/ URI prefix (e.g. /assets/foo-{fingerprint}.js) it stays there and doesn't ever need to change. The internets told me I should write the following rule: location ~ ^/assets/.*-([^.]+)\.(js|css)$ { gzip_static on; # there's also a .gz of the asset expires max; add_header Cache-Control public; add_header Last-Modified ""; add_header ETag ""; break; } I would expect this would result in responses with HTTP code 304 "Not Modified", but what I get is a consistent HTTP 200 (OK) every time. I have tried some other approaches, for instance: a) explicitly setting modification time to a constant point in time in the past; add_header Last-Modified "Thu, 01 Jan 1970 00:00:00 GMT"; b) switching to If-None-Match checks; add_header ETag $1; if_modified_since off; However, the only thing that really worked as needed was this: add_header Last-Modified "Thu, 01 Jan 2030 00:00:00 GMT"; if_modified_since before; I'm lost. This is contrary to everything I thought was right. Please help.
Indefinitely caching a HTTP response via Nginx fails
5 If your using google chrome: Open your site to the page where the changes are not reflecting. press f12 to open inspect window, the developer tool in chrome. Now left click on the reload button for a longer duration continuously, about one second long. You will get three options Go for empty cache and hard reload in this case. Done! Share Improve this answer Follow answered Aug 4, 2017 at 15:07 Dev_ManDev_Man 88611 gold badge1212 silver badges2828 bronze badges 1 This always works and I keep forgetting this solution! :D – shruti iyyer Aug 5, 2017 at 14:30 Add a comment  | 
I've written an app and have been testing it within a project. Any change I make to the project is reflected immediately. But when I make a change to the app and run the install script again, none of the changes are shown. I even look at the files in the site-packages directory and see that the change has been installed. I've tried clearing the browser cache, restarting the browser, trying a different browser, shutting down and restarting the django server, re-sourcing the virtual environment, setting $PYTHON_PATH, and even restarted my system to no avail. This has happened just recently, within the past hour. I was able to make django reflect the changes when I set $PYTHON_PATH and, afterword, re-sourcing the virtual env. But now that won't work, either. I keep thinking it's a caching issue, but I'm not seeing anything on the django cache that would cause this problem. I'm using lighttpd as the server backend if that's an issue.
Django Not Reflecting Changes Made to App
Your question is hot to decompress in javascript right? Read JavaScript: Decompress / inflate /unzip /ungzip strings and How to decompress gzip xhr response in javascript, the should be something usefull
I need to develop super fast jquery based searching, I am using json file to get the data, The size of my file is about 20mb. I am only accessing the file once and caching it. Problem is that it takes a lot of time performing the first search. Can i some how compress my json file? so it takes less time to load.
How to compress json file
You can set the cache from Web API controller like this. var context = HttpContext.Current; if (context != null) { if (context.Cache["courses"] == null) { context.Cache["courses"] = _db.Courses.ToList(); } } For the sake of simplicity, I'm not using any locking here. If your application has high concurrency, it is better to implement a lock while setting the cache. Also, in order for the cache set by We API to be read by MVC, your Web API and MVC controllers must be part of the same application. Just stating the obvious.
I've done the following in my regular MVC controller: public ActionResult GetCourses() { List<Course> courses = new List<Course>(); if (this.HttpContext.Cache["courses"] == null) { courses = _db.Courses.ToList(); this.HttpContext.Cache["courses"] = courses; } else { courses = (List<Course>)this.HttpContext.Cache["courses"]; } return PartialView("_Courses", courses); } The reason I'm caching is because Courses are loaded in two places - a Modal to select a Course, and an Index view that lists all courses. The modal only requires JSON to render (pull data from WebAPI), whereas the Index view is a Razor-generated view (pulled via MVC controller). I'm trying not to query the db again if I already have the Courses data. The above code is for the Index view. Now, for the Modal, I need to send only JSON, but only if courses haven't already been loaded in the Index view. I tried accessing HttpContext from an API controller but it doesn't seem to be accessible in the same manner. How can I check the HttpContext.Cache from a WebAPI controller, and populate it if need be so that the MVC controller can check its contents?
WebAPI HttpContext Cache - is it possible?
Setting the version number in the file works well for us: <script type="text/javascript" src="somefile.js?v=1.0"></script> As long as you change that version number each "release", the browser thinks its a new file. You could do this by simply having a version number in a global file (like a config file or something) and then setting the variable on each script/css tag you wish.
Our asp.net web application allows our (large) .css and .js files to be cached by client browsers for faster performance. But whenever we deploy a new version, we get phone calls from users about how the page looks messy and is full of javascript errors. It turns out, their browser didn't re-download the changed .css and .js files. Ctrl-F5 always fixes it. Is there any way to force a re-download after upgrade deployments, without setting it not to cache (and thus slowing our application down)? I've found this (manually changing reference to every file every deployment): How do I force a given file to expire in the cache? and this (same thing but checksum calculation on every page load): Needed advice on how to implement js/css versioning But surely there are more reasonable solutions than that...?
Elegant way to force client browsers to re-download our asp.net web app's .css and .js files (without totally disabling caching)
try the following function editSkills(projectId, roleId) { $.ajax({ url: '../../Project/EditSkills?projectID=' + projectId + '&roleID=' + roleId, type: "GET", cache: false, data: 'html', success: function (data) { $('#infoPanel').html(data); } }); }
I have this small problem with my MVC program, when run with IE: I have a JQuery function which goes to a controller to get a partial view, which is loaded into a destination <div> element. function editSkills(projectId, roleId) { $.get('../../Project/EditSkills?projectID=' + projectId + '&roleID=' + roleId, function (data) { $('#infoPanel').html(data); }); } The EditSkills() function in the Controller: public virtual ActionResult EditSkills(int projectID, int roleID) { //various pieces of logic return PartialView("EditSkills"); } It seems to work correctly the first time the function is called, but subsequent calls return the same information, instantly, even if the underlying data has been modified. I suspect this is a caching problem (as IE is supposedly overzealous in doing so). As it works perfectly fine in Chrome etc. Are there any options to prevent caching in this case?
JQuery .html() function seems to cache unecessarily in IE
I want to know if firing and handling events could be more cache-friendly than overriding methods when working with classes in C# In general, no. Events are going to require calling out to a separate class instance, which is going to be in a separate memory location. This is going to have the same (or likely even worse) cache issues than virtual method calls. or there is any better strategy than both approaches? Unfortunately, idiomatic C# tends to be non-cache friendly. In order to write cache friendly C# code, you typically want to use struct over class, avoid virtual methods, avoid events, avoid delegates (at least ones with closures), etc. Rico Mariani had a nice blog post on Value based programming which discusses many of these issues in detail.
Reading about the cache-friendly code in this SO question, I want to know if firing and handling events could be more cache-friendly than overriding methods when working with classes in C# (because one of the answers states that one should avoid virtual methods, at least in C++), or there is any better strategy than both approaches?
Are events more cache-friendly code than virtual/overriden methods in C#?
Using Last-Modified requires cooperative coding in your servlet. When you send it to a client, that client will then send back, when requesting the same resource, one of a possible set of headers: If-Modified-Since: If-Unmodified-Since: You would have to process these headers, determine if the content had changed since the given date and then send a 304 response if it hadn't. Lots of manual work. Also note that the Last-Modified date has to be valid (e.g: Tue, 15 Nov 1994 12:45:26 GMT). The simplest route for you would be to ignore Last-Modified for now, and instead use the Cache-Control and Expires headers. Your Expires header needs to be in a valid date format, as described for the Last-Modified header. You can read up more on caching in general, in this excellent document.
I am trying to cache the servlet response but somehow it is not working (Firebug is giving me 200 OK each time i refresh the page). This is the code I added in the servlet: response.setContentType("application/javascript"); long now = System.currentTimeMillis(); response.setCharacterEncoding("UTF-8"); response.setDateHeader("Last-Modified", 0); response.addHeader("Cache-Control", "max-age=5184000"); response.setDateHeader("Expires", now + 5184000 * 1000); response.addHeader("Vary", "Host"); I've also tried with setHeader and with Last-Modified, now. Nothing seems to work. Any ideas? Thanks This is how firebug shows me the response/request headers (when the resource should have been fetched from cache but isnt): Response Headersview source Cache-Control max-age=5184000 Connection Keep-Alive Content-Type application/javascript;charset=UTF-8 Date Thu, 21 Mar 2013 09:53:48 GMT Expires Sun, 31 Mar 2013 16:51:01 GMT Keep-Alive timeout=15, max=99 Request Headersview source Accept */* Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Cache-Control max-age=0
Servlet response should be cached but isn't
I assume you have done the Performance Tuning guide point 1 and 3. It's really helpful. For number 2 you can use the CHttpCacheFilter class CategoryController extends Controller { private $_categoryLastUpdate; public function filters(){ return array( array( 'CHttpCacheFilter + view', 'cacheControl' => " max-age=604800, must-revalidate", 'etagSeedExpression' => function() { return $this->getCategoryLastUpdate(); } 'lastModifiedExpression' => function() { return $this->getCategoryLastUpdate(); } ) ) } public function actionView($id){ $object = Category::model()->findByPk($_GET['id']); $this->render('view', array('object' => $object)); } public function getCategoryLastUpdate(){ if (!isset($this->_categoryLastUpdate)){ $obj = Category::model()->findByPk($_GET['id'], array('select' => 'lastUpdate')); $this->_categoryLastUpdate } return $this->_categoryLastUpdate; } } It basically will calculate the ETag and LastUpdate by the category. And to save the query, it will first only calculate the lastUpdate of the Category object. And for number one, you can always use the CCacheDependency. Just make a field in the thread list object, e.g. lastUpdate. And when a new thread submitted, just update the field and use it for the CCacheDependency. Since I see you are using a very large pagination, I think you want to read about Four Ways to Optimize Paginated Displays (if you use MySQL for your database and thread search/list).
I have built classified website using Yii php framework. Now it is getting a lot of traffic. So I want to using caching to optimize the performance of the website. There are two controllers I want to optimize. One is the thread list controller: (example) http://www.shichengbbs.com/category/view/id/15 The other one the the thread controller: (example) http://www.shichengbbs.com/info/view/id/67900 What I have done: the thread list is cached for 3mins.(The other option is update the thread list only when new thread comes) set the last-modified time HTTP header for the thread view. (expire time is not set, as some user complain that the page appears unchanged after editing) Partial caching the categories navigation fragment.(It appears on the left side of every page) Use htaccess to set expire header for img/html/css/js. Considered database sql caching for the thread list, but not done. As I thought it is the same as 1. What else can I do to improve the website performance?
How use caching to improve the performance of a classified website?
Yes it will cause a new request for the image. If it is ? the image will reload. If you don't want to make new request use # in example background: url(../img/sprite.png#version=20130205) no-repeat -75px -208px;
If I add a cache buster to an image URL in one rule in my CSS background: url(../img/sprite.png?version=20130205) no-repeat -75px -208px; but the same CSS has other versions of the URL without the cache buster background: url(../img/sprite.png) no-repeat 0 0; does that cause another request for sprite.png? Also if the browser parses the non-cache-busted URL first I'd assume it shows the cached image, if it has one, but will then request a new version of the image when it comes to the cache busted version - have I got it right?
Does a cache buster on an image URL in CSS cause an extra request?
What you are looking for is a way of warming up the cache. You could use varnishreplay or a Web crawler, such as Wget or HTTrack to go through your site. Alternatively if you have a sitemap of your pages you could use that as a starting point and warm up the cache by looping over it and issuing requests on the pages using e.g. curl or wget. Using varnishreplay requires you to first run varnishlog and gather a log of traffic before you can use it later for playing back the traffic and warming up the cache. Wget, HTTrack etc. can be pointed to your home page and they will crawl their way through your site. Depending on the size and nature of your site this might not be practical though (for example if you use Ajax extensively). Unless your pages take a very long time to load from the backend server (i.e. Apache), I wouldn't worry too much about warming up the cache. If the TTL for the cached content is high enough most of the visitors will only ever receive cached content anyway.
I have installed the Varnish cache with my Apache web server and configured them correctly. It works OK and I can now access my web pages though Varnish Cache. The default behavior of varnish is to store copies of the pages served by the web server. The next time the same page is requested, Varnish will serve the copy instead of requesting the page from the Apache server. And now comes my question: Is it possible to cache my entire website initially after setting up the Varnish cache, without the need to have a page to be accessed then store it on the cache? This is because, after varnish has been setup, the cache is initially empty, and it will require a page to be accessed in order to be available on the cache. Can this be done without having to access each page manually?
Varnish Cache - Initial cache of web pages
2 Have two or three collections. If you want degrading service with memory availability you can have. a map on the most recent entries, e.g. LinkedHashMap. a map of soft references. a map of weak references. You can control how large each map should be with the knowledge that weak references can be cleared after a minor collection, soft references will be cleared if needed, and the strong references map has the core data which will always be retained. BTW: If you are hitting your memory limit often, you should consider buying more memory up to about 32 GB per JVM. You can buy 32 GB for less than $200. Share Improve this answer Follow answered Jan 7, 2013 at 10:00 Peter LawreyPeter Lawrey 529k8181 gold badges762762 silver badges1.1k1.1k bronze badges 3 How would this make a difference? How do I make sure the cache will not cause OutOfMemmoryError? My application is running on GAE cloud server so adding more memory is not that cheap. – danial Jan 7, 2013 at 13:31 The difference is; You can have a small number entries cached as a minimum and you will not get an OOME unless this small number is still too much i.e. your application was about to die anyway. It is a shame the cloud providers haven't keep up with newer technologies. My 8 year old has 8 GB in his PC as it cost me £24 and buying 4 GB didn't make much sense. – Peter Lawrey Jan 7, 2013 at 14:02 The best way to avoid OOME is to reduce you memory consumption. To do that you need to memory profile your application with VisualVM or ideally a commercial profiler. – Peter Lawrey Jan 7, 2013 at 14:02 Add a comment  | 
Is there a reliable approach to empty the cache before the memory is full? Or even better limit the cache according to current available "actual" free memory (hard-referenced objects)? A soft referenced cache is not a good idea due to high GC penalty, once hit the limit all cache entries need to be reloaded. Also the value runtime.freeMemory() is not that reliable for my purpose because even if it is too low, after the next GC cycle there might be plenty of free space so it's not a good indication of the actual used memory. I tried to figure out how much memory each primitive time would consume so I would know the actual memory usage of the cache and put a limit on it, but couldn't find a reliable way to figure out how much memory would be used to store a String reference of size n.
Java Empty the cache before OutOfMemoryError
You might consider looking at something like s3fs (http://code.google.com/p/s3fs/). This allow you to mount your S3 bucket as a volume on your server instances. You could simply have the code to mount the volume executed on instance start-up. s3fs also has the ability to use local (ephermal) directories as a cache to the s3fs directory so as to improve performance.
I'm working on a WordPress deployment configuration on Amazon AWS. I have WordPress running on Apache on an Ubuntu EC2 instance. I'm using W3 Total Cache for caching and to serve user-uploaded media files from an S3 bucket. A load balancer distributes traffic to two EC2 instances with auto scaling to handle heavy loads. The problem is that user-uploaded media files are stored locally in wp-content/uploads/ and then synced to the S3 bucket. This means that the media files are inconsistent between EC2 instances. Here are the approaches I'm considering: Use a WordPress plugin to upload the media files directly to S3 without storing them locally. The problem is that the only plugins I've found (this and this) are buggy and poorly maintained. I'd rather not spend hours fixing one of these myself. It's also not clear whether they integrate cleanly with W3 Total Cache (which I also want to use for its other caching tools). Have a master instance where users access the admin interface and upload media files. All media files would be stored locally on this instance (and synced to S3 via W3 Total Cache). Auto scaling would deploy slave instances with no local file storage. Make all EC2 instances identical and point wp-content/uploads/ to a separate EBS volume. All instances would share media files. Use rsync to copy media files between running EC2 instances. Is there a clear winner? Are there other approaches I should think about?
Handling Wordpress media files on EC2/S3 with auto scaling
Generally, you should cache Database responses that don't need to be updated frequently, but is accessed frequently. This data need not be from a database — could also be from a file or any type of data store. The key is to feed the most popular things from cache/memory to avoid i/o which is costly. Take a look at this answer for a good explanation of Opcode caching. Opcode caching basically just stores your PHP file on memory, so that it can be interpreted quicker when run. APC works automatically, and detects changes to your file to see if it needs re-caching. Quoting from the above answer: The apc.stat option defines whether APC should examine the last modification date/time of a file to decide between using the opcodes from RAM, or re-compiling the file if it is more recent that the opcodes in RAM. Also, to answer your global vs user specific question. It all depends on exposure, you should cache anything with large amounts of exposure. But generally user-specific data will have less exposure than global data.
Are entire php files added to apc just by using and enabling it? I understand how fetch and store works with variables, but when should this be used? Is the caching of whole files done automatically? If a variable is cached - should it only be a global variable or a user-specific variable?
Php apc opcode cache - caching whole files vs variables
2 I think you're looking for a processor with "scratchpad memory", which is commonly used by GPUs/vector processors in lieu of more sophisticated caching protocols. This is the "programmable cache" you referred to on the Nvidia GPU. To my knowledge no x86 CPUs have this, however it's quite common to see ARM processors with a "core-coupled" low-latency SRAM block that may be used as scratchpad RAM. Share Improve this answer Follow answered Nov 8, 2012 at 17:54 Tony KTony K 28111 silver badge77 bronze badges Add a comment  | 
Is it possible to use CPU's cache the same way as main memory? e.g. saving variables there? CPUs in my lab have plenty of L3 cache (Xeon E5), nvidia's GPU has managable shared-memory/cache, and there are quite some tricks for performance-ehnancement enabled by such programmable cache, is there a way to do the same with CPU's huge amount of cache?
Programmable CPU cache?
When you update/delete your object, a notification is sent to the caching layer to reflect those changes. The cache key might even be broadcasted to another server so it has to carry enough payload to provide enough information for the remote end to flush the relevant entry. But on the other hand it can not be too big in order maximise the throughput. If you turn on the debugging, you will see the following structure (it might vary depending on your persistent object type, identifier - composite or not, etc.): cacheKey = {org.hibernate.cache.CacheKey} |- key = {your.own.serializable.class} |- type = {org.hibernate.type.ComponentType} | |- typeScope = {org.hibernate.type.TypeFactory$TypeScopeImpl} | | |- factory = {org.hibernate.impl.SessionFactoryImpl} | |- propertyNames = {...} | |- propertyTypes = {...} | |- propertyNullability = {...} | |- propertySpan = 2 | |- cascade = {...} | |- joinedFetch = {...} | |- isKey = true | |- tuplizerMapping = {...} |- entityOrRoleName = {java.lang.String} "my.Entity" |- entityMode = {org.hibernate.EntityMode} |- hashCode = 588688 As you can see, Hibernate cache key stores information about the class name, id type, etc. If you have two different types, they will be mapped to two different cache keys hence your problem. In order to fix it, you can create DAO classes for both entities and ensure all calls to persist those entities only go through them and nowhere else. Then, in the update/delete method of both entries simply load and evict the other entity. Another option is to use interceptors which can help achieving the same functionality but to my taste the DAO path is cleaner.
I have following problem. I use JBoss 5.1, JPA/Hibernate with 2-nd level cache. My system has few entities mapping the same database table. Example: Table FURNITURES is mapped by entity 'Furn' and 'Furniture'. These classes CAN NOT be changed. Now the when i change the data of 'Furn' with id 1, the 'Furniture' with id 1 still has the old data. Is there some possibility to evict 'Furniture' after 'Furn' was updated?
Hibernate 2nd level cache update
4 Add this line in each function where the call is made. I use in the find function when consulted a view. ((JpaEntityManager)em.getDelegate()).getServerSession().getIdentityMapAccessor().invalidateAll(); This line clear the cache before run de query. public Entity find(Object id) { ((JpaEntityManager)em.getDelegate()).getServerSession().getIdentityMapAccessor().invalidateAll(); return em.find(Entity.class, id); } Share Improve this answer Follow answered Oct 25, 2012 at 19:33 William CuadrosWilliam Cuadros 11355 bronze badges 1 This works! But only when I created new EntityManager. EntityManager e = Context.getFactory().createEntityManager(); ((JpaEntityManager)e.getDelegate()).getServerSession().getIdentityMapAccessor().invalidateAll(); – Xupypr MV Jan 27, 2016 at 17:26 Add a comment  | 
I have tried disabling L2 cache in EclipseLink with Eclipse indigo by using following properties in persistence.xml:- <property name="eclipselink.cache.shared.default" value="false"/> <shared-cache-mode>NONE</shared-cache-mode> Basically I am testing one scenario whether same object created in two different sessions is hitting database twice or both sessions are referring to same object created in earlier session in memory cache. It should not because L2 cache is disabled by mentioning above properties in persistence.xml My code is as below:- Session session = DataAccessManager.getManager().openSession(); ReferenceObjectRepository referenceObjectRepository = ReferenceObjectRepository.getInstance(); ReferenceObjectKey referenceObjectKey = new ReferenceObjectKey(getStringValue("testCacheByPass.input")); //load object first time. ReferenceObject referenceObject = referenceObjectRepository.load(ReferenceObject.class, referenceObjectKey); logger.log(Level.SEVERE, "Cache ReferenceObject: " + referenceObject); //load object in another session Session sessionNew = DataAccessManager.getManager().openNewSession(); Object dbObject = referenceObjectRepository.load(ReferenceObject.class, referenceObjectKey); logger.log(Level.SEVERE, "DB loaded ReferenceObject: " + dbObject); Please help me whether I have missed something? or do I need to do it some other way??
how to disable cache in eclipselink
Are you handling webView navigation properly? See this tutorial on the official docs: https://developer.android.com/guide/webapps/webview.html#HandlingNavigation if you are just using loadData() then you can try setting hardware acceleration on in the manifest file like this: android:hardwareAccelerated="true" add it at the application level, i.e in the tag of your AndroidManifest.xml file After this point, it really depends on your device. If you have a high end device, images will be rendered quickly otherwise they will take time since webView is using webkit hardware acceleration and this depends on your device configuration. if you still need speed, you can try making a fully native app without webview. Everything will be smooth as butter. No webkit, no html and much greater control. Good luck :-)
I am working on a webView in an app, where content which webview load changes when a button is pressed (two buttons next and previous , they just change the content in webview). But after pressing 3 -4 times it starts to hang there is nothing printed on logcat, the button remains pressed for 15-20 sec and then the next data is loaded. I have used these to clear out webview.db and cache:- context.this.deleteDatabase("webview.db"); context.this.deleteDatabase("webviewCache.db"); webView.getSettings().setRenderPriority(RenderPriority.HIGH); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); But still it hangs.How can I speed it up?Please help? UPDATED: public void setWebView(String QuestionParent,String QuestionNumber) { WebSettings webSettings = questionWeb.getSettings(); webSettings.setDefaultFontSize(24); questionWeb.getSettings().setRenderPriority(RenderPriority.HIGH); questionWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); questionWeb.loadDataWithBaseURL("",integralParse.htmlParse(questionCode,"mnt/sdcard/faData/"+QuestionParent+"/"+QuestionNumber),"text/html","UTF-8",""); } I am using this method on button press. integralParse.htmlParse() method returns a html text .
WebView Loads slowly in android?
You don't want to use WeakHashMap. SoftHashMap would be closer but is not available in the standard library. If I were you I'll look at Guava's cache classes for hints. But here are some additional thoughts: Should scale down when JVM is running out of memory(kind of weak reference). You mean soft reference. But anyways, this requirement smells a bit to me. It can be a valid requirement I'd admit, but it's rare that you really need this. If the size of your records can be reasonably well predicted and if you are planning to have a hard limit on number of records you want to cache, chances are that you don't need this complexity. Third party library shouldn't be use. Everybody mentioned this, and they're right. On the security aspect, efficacy of encrypting data cached in-memory is dubious. You'll have to have the encryption key in-memory as well. I bet there are many things to worry more than attackers reading your memory content.
I want to cache objects in memory. The requirements are as follows: Every record/object is associated with a unique key. 400-500 records/objects to be stored. If the number of records increase beyond the specified limit, then the older records should be evicted. Records shouldn't be stored beyond 2 mins. Should scale down when JVM is running out of memory (kind of weak reference). Third party library cannot be used because its a small module and the intention is just to decrease the unnecessary network access. There are more writes, less reads Security is also a concern here because we are going to cache some sensitive data. This data will be cached in memory. Should I really worry about the security and encrypt the data? I am looking for a Java class which provides a similar functionality. Currently I am thinking of extending WeakHashMap, and implementing various private/public methods to adhere to the requirements. If you have any other idea please share here.
In-memory caching objects in java
EDIT: I assume you are adding the CCSpriteBatchNode node somewhere, although the code you posted does not show it (you also mention, it happens in a switch, so I think in a completely different settings). If so, it will not be deallocated until you remove it from where you added it to. Here, maybe, a clarification is in order. The CCSpriteFrameCache is a cache: a piece of storage where all the sprites get in order to be readily available for reuse. The CCSpriteBatchNode is a mechanism for improving performance in the Open GL layer in principle totally unrelated from the cache. I understand that if you have some sprite used through a batch node still present in some layer/node/scene, than it will not be considered "unused" and will not be removed by your cleanup code. Actually, it is in use. The cached sprite will become "unused" when you remove it from all the nodes that refers to it. As to your question: In other words, is it enough to call "removeUnusedSpriteFrames" at cleanup? Well, I think that it depends on your app what could be considered good cleanup. Removing unused sprites from the cache is certainly ok; but you might also do other things: unloading audio resources you loaded; removing parts of the scene that are not used (and could be reloaded if required); etc. Hope this helps. I don't see any log of the dealloc method of CCSpriteFrameCache. CCSpriteFrameCache is a singleton, so it shall exist for the lifetime of the program (it could be different, but I bet this is the case): CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache]; So, I would not be worried at the fact that the Cache is not deleted; what matters is that its content is emptied.
I got a GameScene class that is not a singleton instance. Hence I allocate and deallocate it every time the user chooses a new level and keep the "static"/"shared" data in a different singleton class (E.g. GameManager). I am using ARC. I would like to understand if my approach is correct under the memory management point of view. In other words, is it enough to call "removeUnusedSpriteFrames" at cleanup? Will this remove all sprites in game-art-forLevelOne-hd.plist? Should I do something also with the CCSpriteBatchNode? -(void) loadGameArtFileForLevelOne //I do this in a switch but this is to simplify the reading { CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache]; [frameCache addSpriteFramesWithFile:@"game-art-forLevelOne-hd.plist"]; CCSpriteBatchNode * sharedSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"game-art-forLevelOne-hd.png"]; } //As dealloc is deprecated for ARC code, I prefer to remove unused sprites and texture on cleanup -(void) cleanup { [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames]; } I added a CCLOG call in the dealloc method of CCSpriteBatch node. When I load the GameScene and then go back to the menu I see the log of "remove unused texture" as expected but I don't see any log of the dealloc method of CCSpriteFrameCache. *!! Warning: See edit below - my mistake!!* EDIT: Sorry, I meant I don't see any log of the dealloc method of CCSpriteBatch This concerns me slightly as I want to "free" and remove all memory related to the Sprites for the level. Once I understood this I will then "optimize" this bit (e.g. have one sprite sheet for each class of level - e.g. world 1 - and one sprite sheet for each background). Any suggestion?
Cocos2d, iOS: what is the correct way to remove sprites from cache?
I have the feeling that the problem is due to the use of the @Cached annotation. In fact if you cache the value manually it works, but if you use the annotation (like described in the doc by the way- it doesn't seem to work. The following piece of code can demonstrate it easily: @Cached(key="page1") public static Result page1() { java.util.Date d = Calendar.getInstance().getTime(); return ok(page.render(d.toString())); } public static Result page2() { Result result = (Result) Cache.get("page2"); if ( result == null ) { java.util.Date d = Calendar.getInstance().getTime(); result = ok(page.render(d.toString())); Cache.set("page2", result); } return result; } With the following page @(date: String) @date And routes GET /page1 controllers.Application.page1() GET /page2 controllers.Application.page2() If you go to http://localhost:9000/page1 the date will change at every calls whereas it will be effectively be cached if you use http://localhost:9000/page2 It's some kind of workaround but it does the job. Regarding your first question "What if the content changes? Does play automatically update the cache?", I think it's not the case and that you have to manually remove the entry from the cache (if you don't want to wait for the expiration date). For example: You put a value in the cache with an expiration time of 10 minutes Another business call makes the value in the cache obsolete and you want the user to be immediately informed so you have to remove the value from the cache immediately Next time the value won't be in the cache and will be recomputed with fresh data It seems that the remove from cache will only be available on version 2.1 (ticket here) and that the workaround is to put something in the cache with the same key and a 1 second expiration.
@Cached(key="homePage") public static Result index() { return ok("Hello world"); } The docs doesn't tell me much about smart caching. Is this really all I have to do? What if the content changes? Does play automatically update the cache? This seems to good to be true. Update 1: For some reason it does not work @Cached(key="homePage") public static Result index() { Logger.info("" + Cache.get("homePage")); return ok("Hello world"); } If I understood it correctly Logger.info("" + Cache.get("homePage")); should only get called once (if the cache is empty). But it gets called every time I refresh the page. Also the result is always null, so it doesn't even work. Any ideas? Update 2: I tried to add the duradion like: @Cached(key="homePage",duration=3000) But it didn't help.
Java Play2 - Smart cache
after they update the picture, add an extra parameter to the url you access to show the image, which here is `displayimage.php'. Most commonly this would be a timestamp. Like in normal case, you would access displayimage.php?id=123123 and after updating the profile pic, to refresh the image, you will need to access displayimage.php?id=123123&time=1000121110. The changing time parameter would force an image reload from the page everytime the user updates the image.
I apologize in advance for my lack of knowledge on this subject; I've looked at lots of other posts but can't get any of their solutions to work for me. Anyway, I'm using a dynamic displayimage.php file to show users' profile pictures on a site I'm working on. The page takes an id parameter, and pulls the image filename from a mysql database. Here's the (abbreviated) code: $id = mysql_real_escape_string($_GET[id]); $table = "images_user"; $idname = "userid"; $uploaddir = "/home/username/uploads/images/user/"; //outside web root $select = mysql_query("SELECT * FROM $table WHERE $idname = '$id' LIMIT 1"); if(mysql_num_rows($select) > 0) { $file = mysql_fetch_assoc($select); header("Content-Type: $file[mimetype]"); readfile($uploaddir.$file[name]); } Currently, because it's generated from a php file, the image is not being cached, which really slows the site down. So I add this: header("Cache-Control: private, max-age=10800, pre-check=10800"); header("Pragma: private"); header("Expires: " . date(DATE_RFC822,strtotime(" 2 day"))); Which solves the problem, great! Now the images are cached, and load super quickly. However, users have the ability to change their profile pictures. When this happens, I save their uploaded picture, delete the old one, and update the database entry to point to the new picture. But now, because the old picture is still cached, they don't see the update unless they manually F5 the page. How can I get it to cache the picture, but force a 're-cache' when the picture has been changed?
Cache php-generated image until it changes
You can configure your dbcontext (or object context) to not use proxy objects. Obviously, this means no change tracking and no lazy loading. If you don't eager load an object's navigation properties, they will simply be null instead of references to proxies. It's worth noting that you can toggle this on and off throughout the context's lifetime, so it's not an all or nothing decision. If you are using DbContext, the syntax is: context.Configuration.ProxyCreationEnabled = false;
I'm trying to figure out how to cache EF query results in an Azure AppFabric cache. Currently I'm using the LoreSoft EntityFramework extensions to deal with the caching (http://bit.ly/LWSywm). It works perfectly with an in memory cache, but not so much with AppFabric across multiple VM's. The issue is that I've got virtual properties in my EF objects, and they're being serialized as Dynamic Proxy objects, which of course can't be deserialized on a different VM, or even after a single VM restarts the application. I only have a few queries I need to cache, so I'd rather not load every single related object manually across the whole project. Is there any way I can serialize an EF object with virtual properties? I don't need the virtual properties to magically start lazy loading again after I deserialize them. I've tried turning off lazy loading the DbContext before serializing the results, but that doesn't work. The only way I've found to get a serializable EF object is the remove all virtual properties. By the way I've looked at the Julie Lerman article here: http://bit.ly/LWToZT Seems like a cool project, but I'm not entirely sure it's going to solve my problem of not being able to serialize EF objects. Don't want to go down that road if I'm just going to end up where I started. Any ideas most appreciated!
Caching Entity Framework results in Azure AppFabric
4 As one of the Infinispan developers, and old JBoss Cache contributor, I'd suggest you have a read to the FAQS. They explain all you need to know about the relationship between Infinispan and JBoss Cache. The point is, unless you're tied to old JBoss Cache, you should be using Infinispan. Share Improve this answer Follow edited Mar 31, 2015 at 10:12 V H 8,48722 gold badges2828 silver badges4848 bronze badges answered Jul 6, 2012 at 14:30 Galder ZamarreñoGalder Zamarreño 5,06722 gold badges2727 silver badges3434 bronze badges Add a comment  | 
I am not native and am poor at English. Please understand the situation. I have been carrying out a comparison of Infinispan and JBoss Cache. Both products are open-source. The JBoss Cache website has at the top the statement 'Project In Maintenance Mode'. Growth of the product will not be carried out, but it is recognized they will carry out stability based changes. Moreover, I recognize Infinispan being a successor of kind to JBoss Cache. However, the point that Infinispan is better than JBoss Cache in regard to performance or stability is unknown to me. Since it is unclear to me after an investigation from the web site, may I have it taught?
comparison of infinispan and Jboss cache
just add a bookmark and fill in the following in the 'url' field: javascript:location.href=location.href; it does make perfectly sense for browsers to revalidate all resources of a given url whenever the 'reload' button is clicked, as this best complies with the intention of the user doing so - in other words, a 'reload' is expected to result in the display of 'fresh' data, instead of simply serving what's already in the browser cache. in addition to this, all major browser have implemented a way of actually fetching every single resource, bypassing any instructions in the http headers to cache it (such as a '304 not modified' status), using shortcuts like SHIFT/CTRL + R/F5.
Sometimes it is useful to measure you site´s performance in a full cached situation. But browsers make this hard to test, because on every manual page refresh it will revalidate all items, which results in a request for every resource on the webserver. Valid cacheitems will respond with a HTTP 304, invalid ones with a 200 OK. So you will end up with wrong timings for this particular use-case because of the latency to your webserver. One solution is to open a new tab, then enter the site´s url, which results in my expected behaviour: Cached items are served from disk. As soon as you hit refresh, the items revalidate again. This workflow (open tab, open tab, and so on) is kinda bad, so i want to ask, if anybody knows a better way to achieve this. Maybe there is a nicely hidden shortcut i missed so far out there on the internet.
How to circumvent cache revalidation on browser refresh?
The reason why the browser was issuing a conditional request is because I was manually refreshing the browser. When a user manually refreshes the page by clicking the refresh button (normal refresh), a conditional request is issued irrespective of the max-age. When a user Ctrl+clicks the refresh button (super refresh), an unconditional request is issued irrespective of the max-age. Under normal navigation (clicking links) the browser won't issue any request when the max-age is valid.
I'm serving an image, with the header set in response as : Cache-Control : max-age=600000 As I understand, the image should now be treated as cache-able for the next 600000 seconds. However i find Chrome constantly issuing a conditional request for the image every time i refresh the page using the last modified date : If-Modified-Since: Thu, 19 Apr 2012 14:51:08 GMT And since the image has not changed on the server, a 304 Not Modified response is issued. So my question is How do i prevent Chrome from issuing a conditional request all together? when i directed that it's okay to cache the image for the next 600000 seconds, then why does it need to check with the server everytime? I would expect it to only check after 600000 seconds.
Http Caching : Cache-Control
Locking the tables is the solution to your problem, I think :)
I have a application that unfortunately uses legacy mysql_* functions with MyISAM tables (bleagh...), so I cannot use transactions. I have code that gets a current balance, checks whether this balance is okay, if yes, it will subtract a quantity and save the new balance. The problem is, I have recently seen an instance where two queries grab the same starting balance, subtract a quantity, then record a new balance. Since they both grabbed the same starting balance, the ending balance after both UPDATES is wrong. 100 - 10 = 90 100 - 15 = 85 When it should be... 100 - 10 = 90 90 - 15 = 75 These requests executed a several minutes apart, so I do not believe the discrepancy is due to race conditions. My initial though is that MySQL cache is storing the result of the identical initial query that gets the balance. I read however that this type of cache is deleted if any relevant tables are modified. I will most likely fix by putting everything into one query, but I still would like to figure this out. It mystifies me. If cache is deleted when a table is modified, then what happened shouldn't have happened. Has anyone heard of something like this, or have any ideas as to why it may have happened?
MySQL SELECT returning old value
5 Using dalli gem, In config/environments/production.rb: config.action_dispatch.rack_cache = { :metastore => Dalli::Client.new, :entitystore => 'file:tmp/cache/rack/body', :allow_reload => false } The above configuration caches the metastore info in memcached but the actual body of the assets to the file system. In config/application.rb: if !Rails.env.development? && !Rails.env.test? config.middleware.insert_before Rack::Cache, Rack::Static, urls: [config.assets.prefix], root: 'public' end Rack::Static usage:   The Rack::Static middleware serves up urls with a matching prefix to a root directory. Here I'm giving config.assets.prefix as my url prefix which defaults to '/assets'. This should serve any assets directly out of the public/assets directory instead of hitting Rails::Cache. This will only work if you run the 'rake assets:precompile' in production, otherwise there will be no precompiled assets in 'public/assets'. Share Improve this answer Follow answered Apr 23, 2014 at 5:55 Ranjithkumar RaviRanjithkumar Ravi 3,40222 gold badges2020 silver badges2222 bronze badges Add a comment  | 
I've recently implemented caching with memcached heroku add-on using Dalli gem for my Rails application. What I find though is when deployed to Heroku, it also caches all my static assets including images, which quickly blows up my memcached size. A sample of heroku logs look like cache: [GET /assets/application.css] fresh app[web.1]: cache: [GET /assets/sign-in-twitter.gif] fresh app[web.1]: cache: [GET /assets/ajax-loader.gif] fresh app[web.1]: cache: [GET /assets/sign-in-facebook.gif] fresh Specifically for index pages, the cache size increases by about 5MB for every different request. Is this behavior configurable? Can I configure memcached to cache only my fragment caches and not proactively cache every image in every page?
Exclude images from caching with Memcached / Dalli
3 Placing a <script src> tag inside the <head> section makes sense – semantically. It does block the browser from rendering anything until the script is loaded but assures that an object (e.g. jQuery) is available in the rest of your code (in the body for example). A common practice is to load a light weight script loading library (HeadJs, LABjs, etc) inside the head section, then load the heavy stuff lazily and/or on-demand. Having said that, HTML5 introduced the async attribute for script tags and re-introduced the defer attribute (docs). So you now have a very good and valid reason for putting <script src> tags inside head sections because: it makes sense the script still loads after the page has finished loading Share Improve this answer Follow edited Sep 11, 2016 at 20:33 Anselm 7,59833 gold badges3030 silver badges3737 bronze badges answered Apr 24, 2012 at 9:14 Salman ASalman A 267k8282 gold badges433433 silver badges526526 bronze badges 1 +1 for 'defer'. Semantically, <script> belongs in the header. Best of both worlds! FTW. – Rap Oct 29, 2013 at 18:32 Add a comment  | 
I mean : I know the JS is cached only if it come from a .js file. Also, 90% of my functions must be rendered when the page (html) is loaded (rendered), so it is better put JS before closing the body tag. (this prevent also to use document .ready(); and the loading of the page itself will be more faster). So, which is the advantage on putting JS in the <head></head>? Expect the "order" of the code, which I don't mind so much to be honest...
Is there a valid reason about putting JS in the head of document?
Personally, I'd stick with APC. HipHop is really only for a certain kind of optimization and, from what I've ready, is a pain in the ass to even get your code working with. It doesn't just seamlessly take what you have and convert it. It's my understanding that there's some PHP that can't be used with it.
I've been using APC for a while for just optcode cache and memcached for object caching. I'm thinking of switching from APC to HopHop. However, it seems that HipHop hasn't had much development lately. Would anyone recommend using HopHop over APC or just stick with APC? Thanks!
HipHop vs APC vs Other or php optcode caching
If you wish to know more about that hash key, I believe it is created in the Mage_Catalog_Model_Product_Image class, at the bottom of the setBaseFile function, it basically takes properties of the image, implodes them together and creates a hash. // add misk params as a hash $miscParams = array( ($this->_keepAspectRatio ? '' : 'non') . 'proportional', ($this->_keepFrame ? '' : 'no') . 'frame', ($this->_keepTransparency ? '' : 'no') . 'transparency', ($this->_constrainOnly ? 'do' : 'not') . 'constrainonly', $this->_rgbToString($this->_backgroundColor), 'angle' . $this->_angle, 'quality' . $this->_quality ); // if has watermark add watermark params to hash if ($this->getWatermarkFile()) { $miscParams[] = $this->getWatermarkFile(); $miscParams[] = $this->getWatermarkImageOpacity(); $miscParams[] = $this->getWatermarkPosition(); $miscParams[] = $this->getWatermarkWidth(); $miscParams[] = $this->getWatermarkHeigth(); } If you need to generate the hash yourself you can use the same steps. Obviously HASH'ing is a one way process, so it is impossible to take the value and find out the image properties.
i want to know how to work the cache of media/catalog/product/cache i don´t know how made the directory structure. My example is media\catalog\product\cache \1\small_image\120x120\9df78dab3d52sd08dse5fw8d27w36e95 a\ b\ d\ ... i don´t understand how to take the number 1 in cache\ next how to take the hash key 9df78dab3d52sd08dse5fw8d27w36e95 and many times in stead of higthxweith(directory) take numberx(directory) I need to know all because i want to made a external CDN and liberate to resize images in my machine. Thx
How to work Cache of media/catalog/product/cache in Magento
Rack::Cache will be working on the level of HTTP traffic. This makes Rack::Cache a suitable replacement for the rails page-level caching (though I do not know if it is a good idea to do so) -- but it can't be used as a replacement for fragment caching. You'll definitely want the fragment caching if it takes a lot of processing time / power to create your fragments and your fragments are re-used several times before they are invalidated. (The usual caching tradeoff.) I could easily image website designs that are useless without fragment caching and the alternative where fragment caching is unnecessary overhead. Most websites will fall somewhere in the middle. So if you wish to use Rack::Cache, I'm sure it is very useful for what it can do, but it can't replace fragment caching.
I am in the process of trying to understand caching options in Rails (and caching in general). I am having a hard time wrapping my brain around the difference between an option like Rack::Cache and the built-in caching options (page, action, fragment). Would I use one OR the other? Or are they for different things? Thanks for any wisdom on the topic!
Rack::Cache vs regular Rails Caching
Your browser is caching the image you need to break the cache by appending a random string to it: http://domain.com/myimage.jpg?random=12893128971844 You can use something like JS math fn: Math.random()
I'm having problems with a function to load an image. Image is loading only the first time, after that I'm getting the same image. Only the first time goes to photoHandler.ashx. What happens here? is jquery caching the image? How to do to load always the correct image?. This is my function: function getObjectFromServer() { var hUrl = "myHandler.ashx"; var data = {}; var data.queryStringKey = "theKey"; $.post(hUrl, data, function(response){ if(response.length>0) { var myObj = jQuery.parseJSON(response); var $photo = $("<img alt='' class='hidden' />").load(function(){ $("#photo-container").append($photo); $photo.fadeIn('slow'); }).attr('src', myObj.photoSrc); //myObj.photoSrc contains: photoHandler.ashx?photoId=anUniqueIdentifier } }); } Edit: If I go to the element with firebug i can see the correct 'anUniqueIdentifier'. MyHandler.ashx always is called. i'm having problems with photoHandler.ashx. I added random but it does not works for me: var randomQS = "&Id=" + Math.round(new Date().getTime() / 1000); //... $photo.fadeIn('slow'); }).attr('src', myObj.photoSrc + randomQS); Update: I resolved it, the problem is PhotoHandler.ashx, this controller is caching the image, this way adding random value to url does not work. Thanks.
Is JQuery caching image?
I don't think you can do that. From the Java Language Specification Sec. 8.1.2: It is a compile-time error to refer to a type parameter of a class C anywhere in the declaration of a static member of C or the declaration of a static member of any type declaration nested within C. It is a compile-time error to refer to a type parameter of a class C within a static initializer of C or any class nested within C.
I have a class called cache. It is an generic, abstract class responsible for handling the global cache for forever type extends the class. My question is, if I have a static variable under the base class, will the static variable be unique per extending type or will it be the same for all types that extend Cache. For example the interface: Cache<K, V> private static Cache<K, V> [creates a cache store on first load] static V get(K key); Then I have an implementing class: PersonCache extends Cache<String, Person> void load(String person); JobCache extends Cache<Integer, Job> void load(Integer key); Which behavior will be expected from Cache's static variable. [The get variable's intention is to be a single public entry point to the JobCache/PersonCache's store] will each type (PersonCache, JobCache] have its own cache store, or will Cache try to store everything it receives?
Static variable in an abstract generic class
4 XML doesn't cache. XML is a file standard. You can cache XML files, but XML has nothing to do with caching. Caching is really just about keeping things around for easy reference. The idea is that if you are using something a lot, you want to keep it around for easy access. It's like books on your desk. You keep the ones you use a lot near you, while the ones you don't you keep on the book case across the room. I also don't think you are really talking about caching here. You want to create an xml file if it doesn't exist. Ok, do you know how to do that? If you want to modify it if it does exist, than just check wherever you are creating the file to see if its there. If it is, load it and modify it. Share Improve this answer Follow answered Nov 18, 2011 at 16:52 CaseyCasey 12.2k1919 gold badges7171 silver badges107107 bronze badges Add a comment  | 
I have a very easy question. I wan't to cache a file. I think the best way is a XML file. There are a lot tutorials how to cache a file, but I don't understand anyone. I wan't to make a XML file, if it doesn't exist. If the file exists I wan't to have the permissions to add XML atributes to it. I know this is a noob question, but I really don't know how I should do this. Could anyone tell me how? I know this this is really bad English, but I hope you'll understand my question.
How to cache a simple XML file?
If your compiler can transform your code to use SSE or AVX, using 64 bit integers instead of 16 bit integers will slow your code down theoretically up to a factor of 4. Even if your compiler cant do this optimization on its own, you can probably manually transform your code so it uses SSE, and gain a good speedup that way. If you cant use SSE, using 32bit integers is probably the best choice, since you still need less memory, and 64bit CPUs are still optimized to handle 32bit values as fast as 64bit values, since many programs arent using 64bit yet.
I have 64-bit machine, and some set of data in range -32000 : 32000, so int16_t is sufficient to store it. Questions: If it is 64-bit machine, then operations on int64_t are atomic, and cost (in terms of speed) the same as operations on int16_t? If so, storing data in 64-bit saves space but not speed? For parallel application, I can actually save speed by storing in int16_t, because cache is also 64-bit, and te more data I store in cache - the faster the threads can access it? Is that right?
64-bit machine, performance for int64 and int16
5 The question you should be asking is if the overhead of creating/populating/maintaining that cache exceeds the cost of generating the cacheable data in the first place. If it costs you $1 to generate some data, $10 to cache it, and $0.8 to retrieve from cache, then you'd have to be able to retrieve that data from cache 50 times to break even. If you only access the cached data 10 times before it expires/invalidates, then you're losing $8. Share Improve this answer Follow answered Oct 27, 2011 at 15:21 Marc BMarc B 358k4343 gold badges427427 silver badges502502 bronze badges Add a comment  | 
Im using Zend_cache to cache results of some complicated db queries, services etc. My site is social, that means that there is a lot of user interaction. Im able to cache users data here and there as well. But taht means, that i will have nearly tens of thousands cache files (with 10 000 users). Is this approach to cache almost everything coming from db still good for performance? Or there are some limits of filesystem? Was looking for some article around, didnt find. Thanks for an advice! Jaroušek
What is the best practice in caching? What are the limits?
I solved my problem using Tokyo Cabinet library. Works faster than using separate files for each object.
Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting answers. We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations. Closed 6 years ago. Improve this question I'm looking for a library for C/C++/Obj-C to maintain on-disk cache for my objects. There is large number of objects (tens of thousands) and each object is 100+Kb in size Objects are constantly accessed/added, sometimes large group of objects is replaced Currently I just store each object in separate file but I don't want to create so many files in the filesystem. Is there any library to work with such cache that will use one/several files instead?
Library for maintaining on-disk cache [closed]
There isn't any difference, not only performance, but also logical. A singleton "caches" its instance in its own static field, so it's logically a cache as well. And your cache should have a singleton-preserving-logic, which most caches don't have. Distributed scenarios are a different story, but in that case you should have the data cached, rather than an instance.
Are there ever any performance (speed & memory) benefits to using a properly-implemented singleton object vs. caching a single object and fetching it out of cache as it is needed?
Singleton or Object Caching?
Yes you can achieve using Reflection. foreach (var t in Cache) { System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry)t; object key = entry.Key; object obj = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { key, 1 }); PropertyInfo prop = obj.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance); DateTime expire = (DateTime)prop.GetValue(obj, null); Response.Write("<br/>" + key + " : " + expire); }
Its simple to add items into this cache: HttpContext.Current.Cache.Add( string key, Object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback ); It would be great if I could query the cache and retrieve the expiry date of each item. Is this possible? As far as I can see I can only retrieve the key name. Reference: http://msdn.microsoft.com/en-us/library/system.web.caching.cache.add.aspx
Querying items in HttpContext.Current.Cache
Ok, it turned out to be quite a dumb but I agree with Joseph Mastey and maybe it will help anyone else ran into this issue. The problem was solved by another extension overriding the same class. So either disable rival extension, edit it or modify tags.
I have a weird problem with Magento cache. I have an extension that have a Block output. If I change anything in the Block/* code it is not reflected in the front-end. If I delete anything in the Block/* it is not reflected at the front end. If I disable the module or delete etc/config.xml it does reflected at the front-end. Cache is disabled and additionally I ran rm -fr var/cache/* before I refresh browsers page. Please advise. UPDATE: This is Magento 1.3.2.3, so there's no System --> Tools --> Compilation menu nor shell/compiler.php. I found the following code in index.php: /** * Error reporting */ error_reporting(E_ALL | E_STRICT); /** * Compilation includes configuration file */ $compilerConfig = 'includes/config.php'; if (file_exists($compilerConfig)) { include($compilerConfig); } but there's no includes folder at all so I think compiler is not the issue. Also here is the code of config.xml of my module: <?xml version="1.0"?> <config> <global> <blocks> <googleanalytics> <rewrite> <ga>Namename_GoogleAnalytics_Block_Ga</ga> </rewrite> </googleanalytics> </blocks> </global> </config> UPDATE: Look for my self-ansver for the solution (quite a dumb).
Magento cache problem
The buffer cache will be used for any access to a filehandle opened against a block device, unless the file handle is opened with O_DIRECT. This includes accesses on behalf of FUSE filesystems. Note that if FUSE does caching as well (I don't know offhand), this may result in double-caching of data; unlike normal in-kernel filesystems, with FUSE the kernel can't safely overlap the page and buffer caches. In this case it may be worthwhile to consider using O_DIRECT in the FUSE filesystem daemon to reduce cache pressure (but be sure to profile first!). For in-kernel filesystems such as UDF, the buffer cache will be used for all IO. For blocks containing file data, the block will simultaneously be in both the buffer and page caches (using the same underlying memory). This will be accounted as page cache, not buffer cache, in memory usage statistics.
I want to know whether the buffer cache in Linux kernel is present for file systems like UDF for DVD and FUSE? I tried to search for this but unfortunately found little information. Thanks.
Linux buffer cache for DVD/FUSE?
5 Usually you implement a deeper pipeline to reduce the cycle time of each pipe stage. Consider two in-order single-issue pipelined processor microarchitectures. uA1 has a 5 stage pipeline and a 2 ns cycle time. uA2 has a 10 stage pipeline and a 1 ns cycle time. A full cache miss must (at least) load an entire cache line from DRAM. Assume that takes 100 ns, including row activation, burst reads of the line words, and row precharge. When uA1 takes a cache miss, it stalls for 100 ns, e.g. 50 clock cycles, e.g. 50 issue slots. When uA2 takes a cache miss, it stalls for 100 ns, e.g. 100 clock cycles, e.g. 100 issue slots. Here the cache miss penalty (expressed in instruction issue slots missed), is twice as large in the more deeply pipelined processor. Share Improve this answer Follow answered Jun 27, 2011 at 23:15 Jan GrayJan Gray 3,4742020 silver badges1515 bronze badges Add a comment  | 
Why is the cache miss penalty greater in a deeply pipelined processor? Is it because the stalling period will be more if the miss occurs at some late stage of the pipeline? Or because there are simply too many instructions in the pipeline?
Cache miss penalty in deep RISC pipeline
May be the code is Jitted the first time you hit the loop. The compile time is what's making it slow? I ran a C++ version of your code and it seems to have about the same latency for every iteration.
I'm doing a bit of benchmarking to test something. I've got a large array of 100 million 64 bit ints, I randomly choose 10 million of those and do a few operations. The indexes are randomly chosen because I'm trying to keep the CPU from caching as much as I can, while still getting an accurate benchmark. The first iteration of the loop takes about .3 seconds, with all of the others only taking .2 seconds. My only guess is that parts of cone[] are still in cache, but I would think with an array of that size it wouldn't be able to store so much. Any other thoughts? Perhaps a JIT issue? static void Main(string[] args) { Int64[] cone = new Int64[100000001]; for (int m = 0; m < 20; ++m) { int[] num2 = new int[10000001]; Random rand = new Random(); for (int i = 0; i < 10000000; ++i) { num2[i] = rand.Next(100000000); } DateTime start = DateTime.Now; for (int i = 0; i < 10000000; ++i) { cone[num2[i]] = i; if (cone[i] > 0) ++cone[i]; } DateTime finish = DateTime.Now; TimeSpan elapsed = finish - start; Console.WriteLine("Took: {0}", elapsed); Thread.Sleep(100); } Console.ReadLine(); }
C# - Why does the first iteration of this loop run slower than the rest?
APC's primary, out the box use is to store the code cache. It can also store data, and indeed, it's quite likely the fastest such cache as it is so closely held (in memory, and the code) to the PHP interpreter. http://uk.php.net/manual/en/function.apc-store.php andthe matching apc_fetch have details of how to use the user/data-caching side of APC. The only downsides are that it has limited space - no more than 32-64MB space allocations for APC's use are normal, and often as much as you would need. For large items, or more than a couple of hundred smaller variables to cache, then something like Memcached, or caching to disk, would be more useful. The other downside is that since the cache is in memory, any variables being cached are onto a specific machine - again, something that Memcached can avoid, but at a cost of time (usually time taken over the local network). In summary, APC is very highly recommended for the code caching (and it has save me literally billions of PHP compilation steps per week), and as a limited, but highly performant 1st-level cache of limited data cache.
I'm running a Zend Framework powered website, it works great, etc. I've the following option apc.cache-by-default sets to on when I check apc.php I can see a lost of file, I'm new to APC, and I'm wondering what kind of surprise could I have with this option. I assume it is only an opcode cache of the files, then no data is cached and I won't see any difference within my website (which needs some realtime data). Am I right? The next step for me is to use APC to cache some db result, but first I'd like to be sure of what a default APC configuration already does for me. Thank you
I installed APC, and now?
Found it. The name of a cache with the useOrigin="true" attribute can be specified on the resolver: <ivysettings> <settings defaultResolver="main"/> <caches> <cache name="main" basedir="${ivy.settings.dir}/ivycache" /> <cache name="nocache" useOrigin="true" /> </caches> <resolvers> <chain name="main"> <filesystem name="filesystem" cache="nocache"> <artifact pattern="${ivy.settings.dir}/ivyrep/[artifact].[ext]" /> </filesystem> <ibiblio name="ibiblio" m2compatible="true" usepoms="false" /> </chain> </resolvers> </ivysettings>
I have a <filesystem> resolver in my ivysettings.xml, along with the central M2 repository, and it all works OK. However, I was wondering whether there is a way to bypass the cache entirely for the dependencies found with the filesystem resolver. I don't need to have them so many times around on my filesystem (once in the directory searched by the resolver, once in the cache, and once in each project's lib folder…).
How can I use a <filesystem> resolver that doesn't copy artifacts to the cache in Ivy?
There are many ways to handle path differences than do not involve loading everything every time. You can, for instance, define a constant and use it as prefix in all your file system operations: define('DOC_ROOT', '/var/www/foo'); require_once DOC_ROOT . '/lib/bar.php'; Or you can rely in your system's DOCUMENT_ROOT variable (if set and correct): require_once $_SERVER['DOCUMENT_ROOT'] . '/lib/bar.php'; Or you can use class autoloading. Or you can use include_path. Apart from that, PHP will always find and parse every file with PHP source code you instruct it to, every time you run your script. You can shorten the second part if you install an opcode cache.
I have once PHP file that I include to pretty much everything I call. This one include file has several other php files that it includes. The reason I use this one file for all my including is because I have path differences between my dev and production server and it is nice to only have to include one file and know that I have the classes that I need right there. Is there any easy way to cache the file, or something to speed up my load times?
How can I speed up my PHP includes?
how can I cause this .js file be cached client side? It would be more reliable to cache it on the server by decorating the action with the [OutputCache] attribute. If you want to cache it on the client you could configure the cache cache location on the client when using this attribute which will send the proper Cache-Control HTTP response header: [OutputCache(Location = OutputCacheLocation.Client, Duration = 20)] public ActionResult Realms() { ... }
Context: ASP.NET MVC 3.0, .NET 4.0, C#, IIS 7 I have a long list of names (of game realms/servers). The realms are stored in a database. I have an Action that returns the list as a JSON code. I reference the list in my .aspx as following: <script type="text/javascript" src='<%= Url.Action("Realms", "Data") %>'></script> Here is an abbreviated action itself: public ActionResult Realms() { var realms = Data.GetRealms(...); var json = JsonSerialize(realms); return Content("realms = {0};".With(json), "text/javascript", Encoding.UTF8); } This list changes very seldom (once a month). Question: how can I cause this .js file be cached client side? Details My problem is that this "file" is being downloaded on each page refresh and accounts for 20% of the traffic.
Enable client side caching for "dynamic" content (asp.net mvc 3.0)
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr CreateFileMapping( IntPtr hFile, IntPtr lpFileMappingAttributes, FileMapProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, [MarshalAs(UnmanagedType.LPTStr)] string lpName); See here for more information http://www.pinvoke.net/default.aspx/kernel32.createfilemapping and http://msdn.microsoft.com/en-us/library/aa366551(v=vs.85).aspx The C# Cookbook contains an implementation of SharedMemoryManager that you can view here: http://csharp.codefetch.com/example/p1/MutexFun/SharedMemoryManager.cs
Does anyone know an Open Source implementation in C# using Shared Memory pre. .NET 4.0 (where we don't have the Memory Mapped file implementations. Preferably using id indexes.
C# Shared Memory Cache
You can consider using Windows Server AppFabric. Intro here http://msdn.microsoft.com/library/cc645013.aspx Windows Server AppFabric provides a distributed in-memory application cache platform for developing scalable, available, and high-performance applications. AppFabric fuses memory across multiple computers to give a single unified cache view to applications. Applications can store any serializable CLR object without worrying about where the object gets stored. Scalability can be achieved by simply adding more computers on demand. The cache also allows for copies of data to be stored across the cluster, thus protecting data against failures. It runs as a service accessed over the network. In addition, Windows Server AppFabric provides seamless integration with ASP.NET that enables ASP.NET session objects to be stored in the distributed cache without having to write to databases. This increases both the performance and scalability of ASP.NET applications.
I have a .NET website which queries the DB using Entity Framework every 3 seconds for the status of the transaction using AJAX and updates the page. This status is set by an external client using a RESTful webservice hosted on another server. I want to avoid hitting the DB every 3 seconds for each transaction so want this information cached in memory. The REST webservice updates the cache and website reads from it. Is there any FOSS or commercial Out of Process Shared Cache library that I can use to speed up the performance?
Out of process caching
There are many ways to cache data. Have a look at memcache as a way to store data in server memory between PHP requests. http://php.net/manual/en/book.memcache.php
I have a big database, and I get data from there and stored in an array. I am working in this data, but I don't want to get every time this data from the database, I want to cache it, it's enought for me to get each 5 minutes. How could I cache an array? Thanks for your help.
Php array cache
Not really, but you can fake it by using version numbers in your keys. For example, if you use keys like this: {entitykey}.{version}.{fieldname} So now your account_1 object keys would be: account_1.1.value_a account_1.1.value_b When you want to remove account_1 from the cache, just increment the version number for that object. Now your keys will be: account_1.2.value_a account_1.2.value_b You don't even need to delete the original cached values - they will fall out of the cache automatically since you'll no longer be using them.
My new PHP application could be sped up with some caching of MySQL results. I have limited experience with memcached, but I don't think it can do what I require. As I am working on a multi-user application I would like to be able to delete several stored values at once without removing everything. So I might store: account_1.value_a = foo account_1.value_b = bar account_2.value_a = dog account_2.value_b = cat Is there a caching system that would allow me to delete based on a wildcard (or similar method) such as "delete account_1.*" leaving me with: account_1.value_a = <unset> account_1.value_b = <unset> account_2.value_a = dog account_2.value_b = cat Thanks, Jim
Memcache alternatives, more control
You can store images in a local SharedObject. By default you're limited to 100KB per site though. http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html You can rely on the browser's own caching but even with that the browser will still make a request to the server to see if it's cache is stale, so local SharedObject caching would be better.
I have a media player, which rotates images for the artist it plays. I load the images dynamically into the flash. The flash downloads the same images from the server over and over, how can i cache the images, so flash grabs them from a local cache and not from the server?
how can i browser cache an image loaded dynamically in flash
First of all you should not use shared contexts. Create new context for each WCF request and dispose context before you end your operation processing! If you need some data caching do it outside of EF. EF itself is not supposed to be used as cache and there is no control of this behavior. If you host your service in IIS you can configure AppPool recycling by specifying Private Memory Limit in advanced settings of the AppPool. But it will simply kill everything running in that AppPool.
I'm using Entity Framework 4.0 behind WCF services. My problem is that the memory used by the programm is growing a lot(start à 200Mo, and I stopped it at ~1.1Go. How can I manage the cache? I mean, I've two datacontext, one of them is never used to read data, so can I disable the cache? And for the other, can I specify the amount of space it cans use? Is there a way to monitor these resources? Is there a way to use less resources? Thank you!
Entity Framework: Cache management?
I think you can have two options to start with: You don't cache anything by default. You can implement with an Observer/Observable pattern a way to trigger an event when the article's view reaches a threshold, and start caching the page. You cache every article at creation In both case, you can use a cron to purge articles which don't reaches your defined threshold. In any case, you'll probably need to use any heuristic method to determine enough early that your article will need to be cached, and as in any heuristic method, you'll have false-positive and vice-versa. It'll depend on how your content is read, if articles are realtime news, it'll probably be efficient as it'll quickly generate high traffic. The main problem with those method is you'll need to store extra information like the last access datetime and its current page views which could result in extra queries.
I have a news site which receives around 58,000 hits a day for 36,000 articles. Of this 36000 unique stories, 30000 get only 1 hit (majority of which are search engine crawlers) and only 250 stories get over 20 impressions. It is a wastage of memory to cache anything, but these 250 articles. Currently I am using MySQL Query Cache and xcache for data caching. The table is updated every 5-10 mins, hence Query Cache alone is not much useful. How can I detect frequently visited pages alone and cache the data?
Caching only frequently used data in PHP
One sweeper can observe many Models, and any controller can have multiple sweepers. I think you should change your logic to use something like that: class SiteSweeper < ActionController::Caching::Sweeper observe Site, Publisher (…) end On PublishersController cache_sweeper :site_sweeper, :admin_sweeper So you don't repeat the logic of cleaning the /admin/site. Call it AdminSweeper, so when something goes wrong you know the only one place that expired the "/admin/sites" action.
I have action caching working on my Sites index, and set up a SiteSweeper that works fine: # app/controllers/admin/sites_controller.rb class Admin::SitesController < Admin::BaseController cache_sweeper :site_sweeper, :only => [:create, :update, :destroy] caches_action :index, :cache_path => '/admin/sites' ... # app/sweepers/site_sweeper.rb class SiteSweeper < ActionController::Caching::Sweeper observe Site def after_save(site) expire_cache(site) end def after_destroy(site) expire_cache(site) end def expire_cache(site) expire_action '/admin/sites' end end But I also want to expire /admin/sites whenever any Publishers are saved or destroyed. Is it possible to have a PublisherSweeper expire the Sites index with something like this? # app/sweepers/publisher_sweeper.rb class PublisherSweeper < ActionController::Caching::Sweeper observe Publisher def after_save(publisher) expire_cache(publisher) end def after_destroy(publisher) expire_cache(publisher) end def expire_cache(publisher) expire_action '/admin/sites' end end I know I can just call expire_action '/admin/sites' within the various Publisher actions. I'm just wondering if sweepers have this capability (to keep my controllers a bit cleaner).
Can Rails sweepers work across different controllers?
When you first asked this question, it was not possible. But it is now possible to do asynchronous memcache operations in the Python version of the SDK starting in version 1.5.4 (see the announcement) and for Java users from version 1.6.0 (announcement)
A typical usage of the memcache (in pseudocode) looks like this: Map data = getFromMemcache(key); if(data == null){ data = doSomethingThatTakesAWhile(); setMemcache(key, data); } return data; If the setMemcache call could be asynchronous, that would be about 10 less milliseconds the user has to wait for their response. The function in this scenario doesn't really care if the setMemcache call was successful, so it doesn't need to synchronously wait for it. Is there a way to do an asynchronous memcache set in app engine? If there isn't currently, is it something that could be possible in the future?
Google App Engine - Is there any way to do an asynchronous memcache set?
It's there, just Adobe glossary missed it. Check the comments at the end of the tag entry: http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_r-s_22.html Also documentation reference here: http://livedocs.adobe.com/coldfusion/8/htmldocs/appFramework_20.html
Is there any way to cache the results of a <cfstoredproc> tag? The <cfquery> tag makes it easy with the cachedwithin attribute but there doesn't seem to be anything for <cfstoredproc>. Am I missing something simple or is this functionality just missing from ColdFusion?
Cache <cfstoredproc> results
Simple: whenever you update a record in the database, you delete any cached copy of it. This forces the cache to be updated the next time the record is requested. It should work like this: $data = retrieveData($id); retrieveData() does this: Is the data for $id in the cache? Good, return it. If it isn't, fetch the data from the database, write a copy to the cache and return it. When updating data: updateData($data); updateData() saves the new $data to the database. It deletes any copy of $data in the cache if there is one. This means that: The first time you retrieve a record from the database there's no cache. Once you have retrieved it though it'll be cached. The next time the same record can be taken from the cache. When the record is updated, the cache is deleted. The next time the record is requested, there's no cache, so it'll be retrieved from the database and the cache updated again. Rinse, repeat.
i understand basic concept of cache , but one thing i cant able to understand , even i saw some example , assume , my first request is 9am , now new update information coming to cache , then another same content request from other user , now system get content from cache file instead of DB, example 1 : i set the cache expire for 1hour , Now time is 9am , 9am : First request : now read the content DB and store into cache file, 9.15AM: second request : now system retrive content from cache instead of retrieve from DB, 9.24am: Few contents are modified in the DB, 9.30am: Third request : NOW system retrieve the content from DB or Cache , How system know DB is updated , This is my doubt : Example 2: If am not set the expiry time :, Then When System retrieve and store the new updated content from the Database to cache file.
Cache invalidation on content update
APC and Xcache are supported via Zend_Cache_Backend_Apc and Zend_Cache_Backend_Xcache
I hear about accelerators such as these in PHP. I believe APC is making it to PHP 6 also. Eaccelerator APC Xcache What's the state of accelerators in Zend? I see a Zend_Cache. Is it the standard and is there more?
What's the current state of accelerators in Zend?
AFAIK, by default, WebView works like a regular Web browser. While it caches things, it still makes requests (with If-Modified-Since and related HTTP headers) to ensure that it has the latest editions. Also, WebView presumably honors other cache control directives sent by the server, perhaps to not cache certain things. You can use getSettings().setCacheMode() on a WebView to modify this behavior somewhat.
My question is, when you are in a webView, and you have gone through several pages. You want to go back. Is the last page you have been to cached, so that you would not need internet connection to go back?
Android: when in web view: Does the browser cache the previous page?
3 I did notice that your tag did not reference the manifest. <html manifest="cache.manifest"> Additionally, you need to ensure that the manifest file uses the "text/cache-manifest" mime type. Also make sure that the manifest has UTF-8 encoding, and not some encoding that the browser has a hard time understanding. Also I can recommend that you load the site in Chrome. If you check the developer log in Chrome, Chrome will write very helpfull error messages that will guide you to where the problem lies. Share Improve this answer Follow answered Apr 7, 2011 at 8:43 MortenMorten 4,55777 gold badges3030 silver badges3131 bronze badges Add a comment  | 
I'm working on a mobile site for the iphone. I've added a cache manifest and loaded it with a list of resources needed for offline capability. The manifest file has the correct content type. If you view the response header for the file, the content type is text/cache-manifest. The manifest file is here: http://hoodisgood.clientsit.es/cache.manifest The site is viewable here (you'll need to take a look on your iphone (or simulator) or on Safari with user agent set to the iphone. http://hoodisgood.clientsit.es/ After viewing the site and bookmarking it to the home screen, I set my iphone to airplane mode and when I try to view the site, I can't. I get an alert that it can't open because it's not connected to the internet. I've specified all the files I need for offline operation in the cache manifest file. Also, correct me if I'm wrong, but with a cache manifest, shouldn't the browser read from the cached source even when the device is online? When I view the site, photos I haven't seen are loaded from the server, as it should be. When I close and reopen, previously viewed images are still loading from the server. Am I doing something wrong? I checked and re-checked, everything seems to be correct, just not sure why it's not working. Thanks.
Offline not working in mobile Safari with cache manifest
There is no reference or limitation of disk space once the application has been installed to the iPhone, iPad, or iPod Touch device. The only limitation would be available disk space (whole disk space available) at time of writing to those directories.
I'm not talking about binary size. I'm talking about the amount of data that can be written to disk during execution inside of certain directories such as Cache or Documents. I can't find an easy answer in the XCode documentation, which is to say I can find none at all. I know there is a limit for the cache directory in the form of "oh hey, your device is crashing now", but I haven't determined the actual number, and I am not sure if the Documents folders or other folders have the same restrictions. Links and numbers are appreciated!
What are the storage limits for iPod/iPad applications?
Answers will vary based on Environments and Technology. Advantages Reduce load on Web Services/ Database Increase Performance Reliability (Assuming db backed cache. Server goes down and db is backed by cache there is no time wasted to repopulate an in memory cache) Disadvantages Could run into issues syncing caches Increased Maintenance Scalability Issues With great power comes great responsibility ;). We ran into an issue where we decided to use the HttpContext.Cache (bad idea) in an application that was distributed. Early on in the project someone deemed to just throw it in there and we didn't run into issues until we went live. Whenever it comes to caching you need to look at the big picture. Ask yourself do we have enough Data, enough Users, or a performance requirement that warrants implementing caching? If you answer yes then you are probably going to need a farm of servers so choose your caching provider wisely. With all that being said, Microsoft has a new cache API AppFabric/Velocity that you could leverage that handles the distribution and syncing of the cache auto-magically. AppFabric caching allows you to do time out eviction, or even built in notification eviction, so as your data chances the caching server takes not of it and periodically the cache client checks in with the server and gets a list of stuff it needs to sync.
What are the advantages and disadvantages of using caching in an asp.net application?
Advantages and disadvantages of using caching in an asp.net application?
There are a variety of options, including using the server's memory: Memcached Database caching Filesystem caching Local-memory caching Dummy caching (for development) Using a custom cache backend To use the server's memory, in settings.py, you should set the cache backend as follows: CACHE_BACKEND = 'locmem://' See the following page in the Django documentation for further information on the various cache backends and for details on how to enable caching: http://docs.djangoproject.com/en/dev/topics/cache/
can I store objects in the servers memory to cache data using django, or do I have to use memcache for that?
does django have a memory based cache or do you have to use memcache?
It appears there is no way to clear the cache. Although, from my experience, Google tends to do it automatically about once a day.
Google Docs Viewer (http://docs.google.com/viewer) creates a cache of a document after the first viewing. To see what I mean, try the following: Upload file.pdf to your server (i.e., http://example.com). Visit http://docs.google.com/viewer?url=http://example.com/file.pdf Upload a new file to replace file.pdf (but use the same name). Revisit http://docs.google.com/viewer?url=http://example.com/file.pdf. Google Docs Viewer still shows the old file.pdf. Anyone know how to correct this? (I have already tried clearing browser cache, switching browsers, and logging in with a different google account to view the link.)
Reload Document into Google Docs Viewer (Clear Cache)
According to the RFC (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1, section 14.9.1) Cache-control: no-cache tells the browser to not use the cached contents without first revalidating with the server. That's why you're seeing the 304's. I think you're looking for Cache-Control: no-store. I'm not sure if you can send no-store via a configuration file. You can, however, set the header explicitly in the response: Response.Cache.SetNoStore(); EDIT: (by OP) What I was looking for was: <clientCache cacheControlCustom="no-store" />
I'm seeing an issue of some static pages that are using the browser cache, which is not desired. To prevent caching, I'm setting <clientCache cacheControlMode="DisableCache" /> in the relevant <location> tag in web.config If I open the page in Firebug (in the Net tab), I see that the Response headers have Cache-Control: no-cache which is correct, but the status of the Response is 304 Not Modified! Isn't that a contradiction? How can I get it to stop caching (i.e. always send a 200 with content)?
cache problem in asp.net
In case anybody else encounters this: the exact caching mechanism is unclear, but restarting the django dev server fixes the problem.
I have gone through the (painful) process of writing a custom template tag for use in Django. It is registered as an inclusion_tag so that it renders a template. However, this tag breaks as soon as I try to change something. I've tried changing the number of parameters and correspondingly changing the parameters when it's called. It's clear the new tag code isn't being loaded, because an error is thrown stating that there is a mismatch in the number of parameters, and it's evident that it's attempting to call the old function. The same problem occurs if I try to change the name of the template being rendered and correspondingly change the name of the template on disk. It continues to try to call the old template. I've tried clearing old .pyc files with no luck. Overall, the system is acting as though it's caching the template tags, likely due to the register command. I have dug through endless threads trying to find out if this is so, but all could find it James Bennett stating here that register doesn't do anything. Please help!
Are Django template tags cached?
Profile it. It depends on the way your users use your site. If it's a web application and your users are likely to interact with it a lot and see most of the layout you designed, you probably want to use a single CSS which is loaded once and then stored in the browser cache. The first time overhead is negligible in this case. If most of your users come with a cold cache and just look at two or three pages, separate CSS files will probably improve their experience. You can't tell without having a look at what the users actually do.
As far as I know, these days there are two main techniques used for including CSS in a website. A) Provide all the CSS used by the website in one (compressed) file B) Provide the CSS for required by the elements on the page that is currently being viewed only Positives for A: The entire CSS used on the site is cached on first visit via 1 http request Negatives for A: if it's a big file, it will take a long time to load initially Positives for B: Faster initial load time Negatives for B: More HTTP requests, more files to cache Is there anything (fundamental) that I am missing here?
Performance, serve all CSS at once, or as its needed?
3 Your expectation is not correct. Queries always query the DB. Always. That's because LINQ is always converted to SQL. To load an object from the context if it's already been fetched and from the DB if it hasn't, use ObjectContext.GetObjectByKey(). Share Improve this answer Follow answered Apr 27, 2010 at 21:16 Craig StuntzCraig Stuntz 126k1212 gold badges254254 silver badges274274 bronze badges Add a comment  | 
I am getting some unexpected behaviour with entity framework 4.0 and I am hoping someone can help me understand this. I am using the northwind database for the purposes of this question. I am also using the default code generator (not poco or self tracking). I am expecting that anytime I query the context for the framework to only make a round trip if I have not already fetched those objects. I do get this behaviour if I turn off lazy loading. Currently in my application I am breifly turning on lazy loading and then turning it back off so I can get the desired behaviour. That pretty much sucks, so please help. Here is a good code example that can demonstrate my problem. Public Sub ManyRoundTrips() context.ContextOptions.LazyLoadingEnabled = True Dim employees As List(Of Employee) = context.Employees.Execute(System.Data.Objects.MergeOption.AppendOnly).ToList() 'makes unnessesary round trip to the database, I just loaded the employees' MessageBox.Show(context.Employees.Where(Function(x) x.EmployeeID < 10).ToList().Count) context.Orders.Execute(System.Data.Objects.MergeOption.AppendOnly) For Each emp As Employee In employees 'makes unnessesary trip to database every time despite orders being pre loaded.' Dim i As Integer = emp.Orders.Count Next End Sub Public Sub OneRoundTrip() context.ContextOptions.LazyLoadingEnabled = True Dim employees As List(Of Employee) = context.Employees.Include("Orders").Execute(System.Data.Objects.MergeOption.AppendOnly).ToList() MessageBox.Show(employees.Where(Function(x) x.EmployeeID < 10).ToList().Count) For Each emp As Employee In employees Dim i As Integer = emp.Orders.Count Next End Sub Why is the first block of code making unnessesary round trips?
Help me understand entity framework 4 caching for lazy loading
The issue is the following: both reads were being performed from cache. I guess caching starts when the file is opened or mmapped, before asking for the data. To verify this, I issued: echo 3 > /proc/sys/vm/drop_caches which flushes out the cache, then, if I run two iterations for getting the same data, the first run is (in my case) 10 times slower than the second.
I am using mmap call to read from a very big file using simple pointer arithmetic in C++. The problem is that when I read small chunks of data (in the order of KBs) multiple times, each read take the same amount of time as the previous one. How can I know if the disk is being accessed to fulfill my request or whether the request is being fulfilled from main memory (page cache) in calls after the first one.
Caching in mmap
Use menu_get_object() which is the proper way to retrieve an object (user, node, etc.) loaded from the URL of a properly declared page. It will return the user object that has already been loaded using the uid found at arg(1) for a menu item which use %user in its path (ie. $items['user/%user'], $items['user/%user/view'], etc. in user_menu(). $account = menu_get_object('user');
I have multiple blocks shown on the user profile page, user/uid On each of them, I need to print the user name. I've been doing a $user = user_load(arg(1)); print $user->name; on each block. Since there is no caching, as you can image the performance is HORRIBLE. Is there either a way to get the user name more efficiently or to cache user_load. Thanks.
Drupal: Getting user name on user account page without breaking performance
As Nathan hints at in his answer, clients can issue a subsequent request with an If-Modified-Since header to determine whether or not their cache is stale. If the client receives a 304 Not Modified response, it will serve the content out of the local cache. According to RFC 2616 (the HTTP 1.1 specification), the presence of must-revalidate within the Cache-control header forces clients to re-check their cache's status with the originating server prior to serving out of the cache.
Ok, I'm confused. I'm trying to send back the magic headers from my server that will prevent a client from hitting the server again until a resource is stale. I understand how ETag or Last-Modified works (Validation) - the client will ALWAYS still hit the server, and the server needs to validate the date or etag against the current value to know whether to bother serving up a new one. Cache-Control and Expires, however, I don't think I understand. I've set the following: Cache-Control: max-age=86400, must-revalidate No matter what I do, my client (my browser, curl, NSURLConnection) always hits the server again on the second request. Is this a client thing? What headers should I send back to get the client to use it's private cache for a certain length of time?
Prevent an HTTP client from hitting a server with cache (iphone)
3 Mark the controller action that generates the list with the OutputCacheAttribute and set the cache location to none to prevent that page from being cached on the client. This should cause the client to request the page again. If the user is using the back button, however, I think that the page is served up by the browser without reloading regardless of the caching. At least in FF I don't see it requesting the page again using Firebug. [OutputCache( Location = OutputCacheLocation.None )] Share Improve this answer Follow answered Dec 30, 2009 at 22:48 tvanfossontvanfosson 528k101101 gold badges698698 silver badges796796 bronze badges 2 If it isn't cached by the browser how could it serve it up again without reloading? – Max Schmeling Dec 30, 2009 at 23:15 I originally thought it would reload, too, but that's not what I'm seeing in FF. – tvanfosson Dec 30, 2009 at 23:18 Add a comment  | 
I have a view that shows a list of items and when you click on one of them it will take you to the items page. I also store a "Viewed" flag in the database for that item. Now, when the user clicks back, the item should be styled differently because of the change in the "Viewed" flag. However, every time I click back, it is as it was before I clicked into the item, and I have to click refresh to see the actual state of the page now. How can I prevent this page from being cached so when a user clicks back they will see the latest version of this site, complete with the new styling?
How can I prevent some of my views in ASP.NET MVC from being cached?
The identifier should be a unique string to represent the cache entry. You might like to name them based on your database tables and fields, e.g. db_tablename_primarykey_1 If you have a method with several arguments, it'll be a pain to make a string containing all of them. Alternatively you can concat a function's arguments and the db_tablename to produce a string for hashing. For example: $identifier = md5('db_tablename_find' . serialize(func_get_args()));
I think I'm getting crazy, I'm trying to implement Zend_Cache to cache my database query. I know how it works and how to configure. But I can't find a good way to set the Identifier for the cache entries. I have a method which searches for records in my database (based on an array with search values). /** * Find Record(s) * Returns one record, or array with objects * * @param array $search Search columns => value * @param integer $limit Limit results * @return array One record , or array with objects */ public function find(array $search, $limit = null) { $identifier = 'NoIdea'; if (!($data = $this->_cache->load($identifier))) { // fetch // save to cache with $identifier.. } But what kind of identifier can use in this situation?
How to use Zend_Cache Identifier?
4 There are a few options now - 1) Check out azuresqlsession.codeplex.com - a custom session provider that works with SQL Azure. It's much faster than the custom provider Microsoft wrote that works with azure table storage. 2) There's also "AppFabric Caching" - a distributed cache that runs in the azure data centers. Microsoft also wrote a custom session provider that works with AppFabric Caching. Currently it's in CTP and you can get it here - portal.appfabriclabs.com - there's a good overview on how to use it here - http://blogs.msdn.com/b/windowsazureappfabric/archive/2010/10/28/introduction-to-windows-azure-appfabric-caching-ctp.aspx?wa=wsignin1.0 - and also in the azure sdk 1.3 labs. I realize the question was asked a while back - I just thought I'd update it if someone stumbled upon the question after a google/bing search. Good times! about.me/ehuna Share Improve this answer Follow answered Jan 16, 2011 at 9:34 ehunaehuna 11111 silver badge66 bronze badges Add a comment  | 
hey guys if i have an azure web app running under multiple instances how do i use asp.net cache. has the azure team written any cache providers for azure? i read somewhere they are going to support velocity in future but if i have to go live with some app in next couple of months what is the best way i can cache my data (i dont want to use sql server cache as that simply defeats my purpose of caching in the first place)
how to use asp.net cache on windows azure with multiple instances
ob_start() can do what you want: ob_start('store_output'); function store_output($output) { // do something with $output return $output; } When the output buffer is flushed, the function will be called. Output buffers can be nested.
I have a set of custom PHP scripts. They load a main PHP file (to include other files, set settings, etc.) From this script I'd like to insert a callback function that is called by the scripts that included the main file just before ending. What I intend to do is make a simple custom output cache with ob_get_contents(). I want to do ob_start() in main.php, then have the callback function store the output.
PHP callback just before script dies
In effect, that is exactly what JTable allows. afaik if the getRowCount() method reflects exactly how many records there are, then when the cells are painted, only the visible part is queried. I don't think prefetching by listening on the viewport would be any faster. you could wait for all getvalue requests. record those, return "null" or the already cached value. then after a getvalue isn't called for say 20 ms do the actual request for all the recorded cells. and fire rowUpdated events on the model so JTable repaints again. **[edit]**You could maintain a list of the last records queried on the model. your list doesn't need to be any longer than the amount of rows visible on the screen. after getValue() isn't queried for a few ms, you could perform this async bulk request to the back-end The only catch here is the sorting/filtering algorithm. When you query the viewport and let the data depend on that, then there is a 1-1 relation between your data and the view. Something which JTable itself doesn't have. But i guess there is no way around that. I would enable the IDE debugger to dig through sun code. and then see how their rendering implementation finds out which rows to repaint. i don't know by heart.
Scenario: you are using a JTable with a custom TableModel to view the contents of some collection located in a database or on the network or whatever. The brute force way to make this work is to load the whole collection at once. Let's say that isn't practical because of the resources needed. The simple way around that problem is to fetch rows on demand, one row at a time, as the JTable renders each row, and calls TableModel.getValueAt(); cache as necessary. This causes a lot of hits to the database, though. Is there a way to listen to scroll/viewport events for a JTable, to figure out what rows it is going to display before it renders each cell? If so, I would like to intercept and cause my custom TableModel to prefetch one page at a time. edit: just to clarify, the point here is to be able to fetch the contents of a group of visible table rows in one batch, rather than having to fetch the contents of each row by itself.
JTable + TableModel cache fetch event for lazy instantiation?
Before you get too far through your implementation, you should know that mysql does its own query caching and it has several major advantages over your implementation: The cache is shared among all PHP requests. Cached results are automatically cleaned up when the table data changes. The cache is limited to a certain memory size (rarely-used queries will be dropped out of the cache)
Im doing a database class in PHP and I want to make cache of the result of the querys in a associative array, My idea is to use the sql statment as the index of the cache array, its could be a good idea? or should I use a md5 from the sql? class DB{ const HOST = 'localhost'; //Your Database Host! const USER = 'user'; //Your Database Username! const PASSWORD = 'pass'; //Your Database Password! const DATABASE = 'database'; //Your Database Name! private static $Instance; private static $cache = array(); private function __construct(){ self::$Instance = mysql_connect(self::HOST, self::USER, self::PASSWORD) or die("Could not connect to database server<br/><b>Error:</b>".mysql_error()); mysql_select_db(self::DATABASE) or die("Could not connect to database<br/><b>Error:</b>".mysql_error()); return self::$Instance; } public static function DB(){ if(!isset(self::$Instance)){ $c = __CLASS__; new $c(); } return self::$Instance; } public static function QueryUnique($query){ $query = "$query LIMIT 1"; //$h = md5($query); $h = $query; if(isset(self::$cache[$h]))return self::$cache[$h]; $result = mysql_query($query, self::DB()); self::$cache[$h] = mysql_fetch_array($result); return self::$cache[$h]; } } Good Day
PHP theres some Impact using long text in a associative array?
Even if the DNS is not cached local to the machine, it will likely be cached somewhere along the DNS chain between the machine and the name servers, at least for a short while. My understanding is this situation would usually be handled with IP takeover where you just make the new machine 111.111.1.1. Probably a question for serverfault.
Suppose the following: I have a database set up on database.mywebsite.com, which resolves to IP 111.111.1.1, running from a local DNS server on our network. I have countless ASP, ASP.NET and WinForms applications that use a connection string utilising database.mywebsite.com as the server name, all running from the internal network. Then the box running the database dies, and I switch over to a new box with an IP of 222.222.2.2. So, I update the DNS for database.mywebsite.com to point to 222.222.2.2. Will all the applications and computers running them have cached the old resolved IP address? I'm assuming they will have. Any suggestions along the lines of "don't have your IP change each time you switch box" are not too welcome as I cannot control this aspect of the situation, unfortunately. We are currently using the machine name of the box, which changes every time it dies and all apps etc. have to be updated with the new machine name. It hurts.
Do connection string DNS lookups get cached?
It's going to depend on many things such as disk speed, network latency and the amount of data, so some experimentation might be the best way to get an idea. I recommend you have a look at http://ehcache.org/, it might come in handy.
I am at a point where I need to take the decision on what to do when caching of objects reaches the configured threshold. Should I store the objects in a indexed file (like provided by JCS) and read them from the file (file IO) when required or have the object stored in a distributed cache (network, serialization, deserialization) We are using Solaris as OS. ============================ Adding some more information. I have this question so as to determine if I can switch to distributed caching. The remote server which will have cache will have more memory and better disk and this remote server will only be used for caching. One of the problems we cannot increase the locally cached objects is , it stores the cached objects in JVM heap which has limited memory(using 32bit JVM). ======================================================================== Thanks, we finally ended up choosing Coherence as our Cache product. This provides many cache configuration topologies, in process vs remote vs disk ..etc.
Java object caching, which is faster, reading from a file or from a remote machine?
"Does mod_wsgi/Python include internal optimizations that would stop complete execution? Does it guess the output is deterministic and cache?" No. The problem is (generally) that you have a global variable somewhere in your program that is not getting reset the way you hoped it would. Sometimes this can be unintentional, since Python checks local namespace and global namespace for variables. You can -- inadvertently -- have a function that depends on some global variable. I'd bet on this. What you're likely seeing is a number of mod_wsgi daemon processes, each with a global variable problem. The first request for each daemon works. Then your global variable is in a state that prevents work from happening. [File is left open, top-level directory variable got overwritten, who knows?] After the first few, all the daemons are stuck in the "other" mode where they report the answer without doing the real work.
I have been trying to track down weird problems with my mod_wsgi/Python web application. I have the application handler which creates an object and calls a method: def my_method(self, file): self.sapi.write("In my method for %d time"%self.mmcount) self.mmcount += 1 # ... open file (absolute path to file), extract list of files inside # ... exit if file contains no path/file strings for f in extracted_files: self.num_files_found += 1 self.my_method(f) At the start and end of this, I write obj.num_files_found To the browser. So this is a recursive function that goes down a tree of file-references inside files. Any references in a file are printed and then those references are opened and examined and so on until all files are leaf-nodes containing no files. Why I am doing this isn't really important ... it is more of a pedantic example. You would expect the output to be deterministic Such as Files found: 0 In my method for the 0 time In my method for the 1 time In my method for the 2 time In my method for the 3 time ... In my method for the n time Files found: 128 And for the first few requests it is as expected. Then I get the following for as long as I refresh Files found: 0 In my method for the 0 time Files found: 128 Even though I know, from previous refreshes and no code/file alterations that it takes n times to enumerate 128 files. So the question then: Does mod_wsgi/Python include internal optimizations that would stop complete execution? Does it guess the output is deterministic and cache? As a note, in the refreshes when it is as expected, REMOTE_PORT increments by one each time ... when it uses a short output, the increment of REMOTE_PORT jumps wildly. Might be unrelated however. I am new to Python, be gentle Solved Who knows what it was, but ripping out Apache, mod_python, mod_wsgi and nearly everything HTTP related and re-installing fixed the problem. Something was pretty broken but seems ok now :)
Is mod_wsgi/Python optimizing things out?
3 For windows, you should look at CreateFile function, with flags FILE_FLAG_NO_BUFFERING and FILE_FLAG_WRITE_THROUGH. ( http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx ). But then you'll have to use windows functions for reading and writing : SetFilePointer, WriteFile, ReadFile... Share Improve this answer Follow answered Mar 5, 2010 at 14:02 imaspyimaspy 3922 bronze badges Add a comment  | 
In C file I/O, the O_DIRECT flag can be used to minimize cache effects for a file being open()ed. I understand that this is not a POSIX feature, has been present in the Linux kernel since version 2.4.10, and that Linus is opposed to the interface in general. Under NetBSD, it seems to work as advertised. Example call: int fd = open(filename, O_DIRECT); I am attempting to write some low-level disk benchmarking utilities, and using O_DIRECT looks to be a potentially good way of measuring the disk and drive performance without the effects of the OS filesystem/block cache. Ideally, I would like to be able to run the benchmark on Linux, Windows (Cygwin is OK), Mac OS X, and BSD systems. Is O_DIRECT the best way to bypass the OS disk caches, in terms of portability and reliability for benchmarking? Are there alternatives?
Portability of open(...O_DIRECT) in C?