Monday, December 28, 2015

Are scoped variables faster?

tldr: No

At the recent ColdFusion conference, it was recommended that you always scope variables for a speed increase. Simply including a variable #like_so# requires the engine to potentially look through several scopes until it finds the correct one.

The main place this would matter, of course, is inside a large loop. Specifically, you would want to scope fields inside a query loop.

I wrote the following code to test this out. q is a query of 10,000 rows.
 <cftimer label="unscoped" type="debug">  
      <cfloop query="q">  
           <p>#p1# #p2# #p3# #p4# #p5# #p1# #p2# #p3# #p4# #p5#</p>  
      </cfloop>  
 </cftimer>  
 <cftimer label="scoped" type="debug">  
      <cfloop query="q">  
           <p>#q.p1# #q.p2# #q.p3# #q.p4# #q.p5# #q.p1# #q.p2# #q.p3# #q.p4# #q.p5#</p>  
      </cfloop>  
 </cftimer>  

Results:
unscoped: 48ms
scoped: 75ms

Several runs (and reversing the order of two loops) all gave similar numbers on both CF10 and CF11. So I'm afraid that, at least for Adobe implementations of Coldfusion, you are better off not scoping your variables.

(I still advise scoping arguments, though.)

No comments:

Post a Comment