Created
September 7, 2021 21:53
-
-
Save trycf/32f6ad1329d101b64fd02ddf3f6c4b89 to your computer and use it in GitHub Desktop.
TryCF Gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
// the root struct we will test against | |
myStruct = { | |
apiResponse = { | |
body = "i am the body", | |
headers = { | |
status_code = "405", | |
status = { | |
code: "200" | |
} | |
} | |
} | |
}; | |
// these are the keys we will test. Contains failures and successes | |
keysToTest = [ | |
"apiResponse.headers.status_code", // true | |
"apiResponse.headers.error", // false | |
"apiResponse.headers.status.code", // true | |
"apiResponse.headers.status.name" // false | |
]; | |
// how many iterations | |
count = 10000; | |
// init the udf | |
boolean function structHasKey( required struct struct, required string key ) { | |
var keyArray = listToArray( arguments.key, "." ); | |
var subStruct = arguments.struct; | |
for ( var item in keyArray ) { | |
if ( !subStruct.keyExists( item ) ) { | |
return false; | |
} | |
subStruct = subStruct[ item ]; | |
} | |
return true; | |
} | |
// TEST 1: UDF | |
writeOutput( "<h2>UDF</h2>" ); | |
start = getTickCount(); | |
for ( a=1; a < count; a++ ) { | |
for ( key in keysToTest ) { | |
result = structHasKey( myStruct, key ); | |
} | |
} | |
writeOutput( "<h3>#getTickCount() - start# ms</h3>" ); | |
// TEST 2: IsDefined() | |
writeOutput( "<h2>IsDefined</h2>" ); | |
start = getTickCount(); | |
for ( a=1; a < count; a++ ) { | |
for ( key in keysToTest ) { | |
result = isDefined( "myStruct.#key#" ); | |
} | |
} | |
writeOutput( "<h3>#getTickCount() - start# ms</h3>" ); | |
// TEST 3 keyExists() | |
writeOutput( "<h2>KeyExists</h2>" ); | |
start = getTickCount(); | |
for ( a=1; a < count; a++ ) { | |
result = ( | |
myStruct.keyExists( "headers" ) && | |
myStruct.headers.keyExists( "status_code" ) | |
); | |
result = ( | |
myStruct.keyExists( "headers" ) && | |
myStruct.headers.keyExists( "error" ) | |
); | |
result = ( | |
myStruct.keyExists( "headers" ) && | |
myStruct.headers.keyExists( "status" ) && | |
myStruct.headers.status.keyExists( "code" ) | |
); | |
result = ( | |
myStruct.keyExists( "headers" ) && | |
myStruct.headers.keyExists( "status" ) && | |
myStruct.headers.status.keyExists( "name" ) | |
); | |
} | |
writeOutput( "<h3>#getTickCount() - start# ms</h3>" ); | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment