devxlogo

Friend Procedures are faster than Public ones

Friend Procedures are faster than Public ones

It might surprise you to learn that Friend procedures are sensibly faster than Public ones. You can prove this yourself by creating an ActiveX EXE project with one Private class and one Public class (Instancing = MultiUse), and then add the following code in both class modules:

Public Sub PublicSub(ByVal value As Long)    'End SubPublic Function PublicFunction(ByVal value As Long) As Long    'End FunctionFriend Sub FriendSub(ByVal value As Long)    'End SubFriend Function FriendFunction(ByVal value As Long) As Long    'End Function

Then in a form module create a loop that executes each procedures a large number of times. For example, to see the difference in timing on a Pentium II machine you should perform about 1,000,000 calls to each routine. These are the timings I got:

For the Private class modules, one million iterations of either the Public Sub or Function routines took 0.46 seconds, while their Friend counterparts took only 0.05 and 0.06 seconds respectively (about 8-9 times faster). Timings are virtually the same with the MultiUse class module.

The probable explanation for this weird behavior is that Friend procedures don’t undergo the overhead of marshaling and unmarshaling code. (Keep in mind that Public procedures can be called from outside the current project, in which case COM must marshal data back and forth.) While this explanation make sense, however, it doesn’t explain while even Public routines in Private classes – that can’t be called from outside the current program – show the same overhead. Moreover, relative timings don’t change if the project type is changed to Standard EXE, where all classes are Private and can’t be called through COM. In other words, it seems that there is some room for improving the code generated by the compiler.

The good news is that the overhead is really negligible in most cases, especially when the routine contains some complex and time-consuming statements.

Even though you should never select the Friend qualifier for performance reasons, keep in mind that Friend procedures have other advantages over Public ones, most notably the capability to accept and return UDT variables that are defined in a BAS module.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist