Apex Caching Performance Impact

Apex Caching is great for saving some basic Id’s of a user like his Account, Contact Id’s after he logs in so you don’t have to query for them. Reduces the amount of queries and improves speed. Caching is good for saving large blobs that don’t change frequently.

Generic Cache Service to put, retrieve and remove cached item

public with sharing class App_Service_Cache {

		private Boolean cacheEnabled;

		public App_Service_Cache() {
			  cacheEnabled = true;
		}

    public Boolean toggleEnabled() { // Use for testing misses
        cacheEnabled = !cacheEnabled;
        return cacheEnabled;
    }

    public Object get(String key) {
        if (!cacheEnabled) return null;
        Object value = Cache.Session.get(key);
        if (value != null) System.debug(LoggingLevel.DEBUG, 'Hit for key ' + key);
        return value;
    }

    public void put(String key, Object value, Integer ttl) {
        if (!cacheEnabled) return;
        Cache.Session.put(key, value, ttl);
        // for redundancy, save to DB
        System.debug(LoggingLevel.DEBUG, 'put() for key ' + key);
    }

    public Boolean remove(String key) {
        if (!cacheEnabled) return false;
        Boolean removed = Cache.Session.remove(key);
        if (removed) {
            System.debug(LoggingLevel.DEBUG, 'Removed key ' + key);
            return true;
        } else return false;
    }
}

Test cache get is faster than query

@isTest
private class App_Service_Cache_Test {

	@isTest
	static void testCachePerformance() {
		App_Service_Cache appCache = new App_Service_Cache();
		Map<String, String> communityUser = App_Global_Test.setupCommunityUserReturnIds();
		Id userId = communityUser.get('UserId');
		long startTime = System.currentTimeMillis();
		List<Contact> currentContact = [select Id, AccountId from Contact where Id IN (Select ContactId from User where Id=:userId)];
		long elapsedTime = System.currentTimeMillis() - startTime;
		appCache.put('userId', currentContact, 2000);
		System.debug(elapsedTime);

		long startCacheTime = System.currentTimeMillis();
		appCache.get('userId');
		long elapsedCacheTime = System.currentTimeMillis() - startCacheTime;
		System.assert(elapsedCacheTime < elapsedTime);
	}
}

1 Comment

  1. Hemil says:

    can you please tell me a what is App_Global_Test.setupCommunityUserReturnIds() in Test cache get is faster than query section

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s