K2 extra fields are stored as a JSON string in the #__k2_items database table. K2 utilizes a custom library (JSON.php) to encode and decode the extra fields.
The JSON.php library consists of: three classes, 800+ lines of code, many control statements, and moreover, many function calls. In short, the library has many aspects that impact a site's performance. Fortunately there's a way to improve your K2 extra fields performance.
The K2 extra fields performance solution
There are 2 built-in PHP functions that can replace the JSON.php BIG & SLOW functions, they are: json_decode & json_encode, these 2 functions are installed by default for PHP 5.2.0 and later versions, so you can use them easily without any prior configuration.
Time to get your coding hands dirty.
Find the following two K2 files:
For each file of them, you will do 3 steps:
- Find all occurrences of $json->decode and replace with json_decode.
- Find all occurrences of $json->encode and replace with json_encode.
- Comment all occurrences of these lines (comment = add // in fornt of each line):
- require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'lib'.DS.'JSON.php');
- require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
- $json = new Services_JSON;
This hack is highly recommended for sites that utilize many (20+) extra fields. Don't forget to clear your Joomla! site cache (if you're using it). You should see an instant boost in performance, especially in K2 search.
This hack is only necessary for sites that are using K2 v2.7.0 or lower, this hack has been applied to K2 v2.7.1, refer to this pull request
This hack is critical, so make sure to perform a backup before executing this or any hack. In this case, you could simply make a copy of each file before making modifications. Since is a core hack, you will need to re-apply it after each K2 update.
If you have any questions or suggestions, feel free to comment on this post, or contact me directly via email or social media (on the above right corner of this page).
Has this K2 Hack improved your Joomla! website performance? We want to know :)