StructCount vs StructIsEmpty performance
There was a question the other day on the CFML slack channel asking how you’d find if a struct was empty. I posted an answer that you could use StructCount
to do it, someone else posted StructIsEmpty
. I have to admit, I didn’t know about StructIsEmpty
. This lead onto which one is more performant. When the struct is empty I’d expect there to be no difference, but what if the struct had 1,000,000 keys? I thought I’d test and post the results.
i = 0; map = {}; while(i++ < 1000000) { map['key_#i#'] = i; } s = getTickCount(); result = StructIsEmpty(map); e = getTickCount(); WriteDump({ "ms": e-s, "result": result }); s = getTickCount(); result = StructCount(map); e = getTickCount(); WriteDump({ "ms": e-s, "result": result });
The outcome surprised me.
ms 0 result NO ms 0 result 1000000
Just for good measure, I thought I’d also try with an ordered struct (structNew("ordered")
) and the result was the same. So there you go a simple question lead to an interesting investigation!
neoplay Java also has the .isEmpty() method as well as .size() method. Size needs to be calculated, isEmpty() can just check for 1 key/value and then stop at that point.
It may be obvious to you, but I didn’t know if:
it does use size() or isempty()
that java’s size() method calculates on the fly
So the investigation was to see if calling size counts the items when called. From the timings it seems that internally the size is updated as key/values are added.
You must be logged in to post a comment.