I am trying to write a MySQL stored function to generate vU UIDs as described in RFC 4122, section 4.4 ( http://www.ietf.org/rfc/rfc4122.txt ). My initial naive effort after a few tricks is as follows:
CREATE FUNCTION UUID_V4() RETURNS BINARY(16) READS SQL DATA BEGIN SET @uuid = CONCAT( LPAD( HEX( FLOOR( RAND() * 4294967296 ) ), 8, '0' ), LPAD( HEX( FLOOR( RAND() * 4294967296 ) ), 8, '0' ), LPAD( HEX( FLOOR( RAND() * 4294967296 ) ), 8, '0' ), LPAD( HEX( FLOOR( RAND() * 4294967296 ) ), 8, '0' ) ); SET @uuid = CONCAT( SUBSTR( @uuid FROM 1 FOR 12 ), '4', SUBSTR( @uuid FROM 14 FOR 3 ), SUBSTR( 'ab89' FROM FLOOR( 1 + RAND() * 4 ) FOR 1 ), SUBSTR( @uuid FROM 18 ) ); RETURN UNHEX(@uuid); END
The above function is rather slow: almost 100 times slower than the built-in UUID() , according to the MySQL BENCHMARK() function. With the exception of writing UDF using the MySQL C API, are there any improvements I can make here, say, save an order of magnitude from its runtime?
If there is an existing, well-priced UDF or UDF stored procedure, I would also be happy to know about it.
source share