Improving the performance of friends_check_friendship in BuddyPress

Are you using friends_check_friendship() function in your code to test the user friendship relationships. If yes, this post may help you. A slight change in the order of the passed arguments can help us cut down the queries from  O(n) to O(1).

Let us see it with an example. Say you have the code in your members loop like this

In case you are using the above code inside the members loop, if one of the user is logged in user, we can save the queries from n(number of members in the loop) to 2.

Depending on which user id is used as the first argument ($user_id1), It can cause either 2 or n+x(where n is the number of members in the loop and x is the number of queries used to cache the friendship ids) query.

If you use the logged in user id as the first id( bp_loggedin_user_id() or get_current_user_id()), There will be only two extra query(if at all) for checking relationship with all the members in the loop. The first check caches the friend ids and the friendship ids and the rest of the test uses it from cache.

On the other hand, if you used the varying member id(current loop member id, bp_get_member_user_id() ) as the first argument, the number of queries will be linear. Depending on how many members are there in the loop, there will be n number of queries.

Remember to always use the non varying user_id as the first argument for the function friends_check_friendship() to avoid extra queries. If you are already doing that, you are awesome!

2 Responses to Improving the performance of friends_check_friendship in BuddyPress

  • Interesting to know that.

    • Even I was surprised due to the abnormal no. of queries on members directory and then found it at the reason. It is justified though.