Orange is my favorite color

While the built-in CreateUUID() of ColdFusion has a very high probability of being unique (because it ties the values to your MAC address in some fashion), it is quite slow. Check this comparison:

<cfset uuid = createobject("java", "java.util.UUID") />

<cfset start = getTickCount() />
<cfloop from="1" to="1000" index="ii">
	<cfset x = createUUID()  />
</cfloop>
<cfdump var="createUUID() Time elapsed: #getTickCount() - start#" />

<cfset start = getTickCount() />
<cfloop from="1" to="1000" index="ii">
	<cfset x = uCase(removeChars(uuid.randomUUID().toString(), 24, 1))  />
</cfloop>
<cfdump var="java.util.UUID Time elapsed: #getTickCount() - start#" />

Results? On my duo-core Thinkpad X61, CreateUUID() takes around 15s and java.util.UUID takes 16ms. That’s right: 15000ms for createUUID() and 16ms for java.util.UUID. 937 times faster.

Concerned about uniqueness? The version 4 UUID produced by java.util.UUID has 2122 significant bits. The chances of collision given a relatively normal distribution is incredibly small.

If you need to generate lots of keys for a database or in a loop, you might consider using this alternative for a turbocharge.

7 Comments

  1. John Whish said:

    on March 20, 2009 at 1:04 am

    Good tip, thanks. I currently use mssql GUID’s in my database and have been noticing a performance issue when looping through inserts and using Insert( “-”, CreateUUID(), 23 ).

  2. Henry Ho said:

    on March 20, 2009 at 10:23 am

    @John, why don’t you use MS-SQL’s NEWID() instead?

  3. David Lakein said:

    on March 20, 2009 at 12:42 pm

    Which version of CF?

  4. brian said:

    on March 20, 2009 at 1:56 pm

    @David – my tests above were on CF 8.0.1. You’ll need CF8 (Java 5) to use java.util.UUID natively I believe. There are other open source packages available you could use with CF7.

  5. Brad Wood said:

    on March 20, 2009 at 8:03 pm

    Yes, Java.util.UUID was introduced in Java 5, so if you are on ColdFusion 6 or 7, you can use JUG. I have tested it and it is also very fast:
    http://jug.safehaus.org/

  6. Nathan D said:

    on March 20, 2009 at 10:16 pm

    That difference is with the string operations you are doing too, right? Pretty amazing.

  7. brian said:

    on March 21, 2009 at 6:19 am

    @Nathan – I thought the same thing; removeChars(), uCase()… surprising.

{ RSS feed for comments on this post}