March 6, 2019
StructCount vs StructIsEmpty
Comments
(3)
March 6, 2019
StructCount vs StructIsEmpty
I try to bend the internet to my will.
Newbie 34 posts
Followers: 24 people
(3)

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!

3 Comments
2019-03-08 12:30:59
2019-03-08 12:30:59

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.

Like
(1)
2019-03-08 10:49:00
2019-03-08 10:49:00

I assume that the implementation of StructIsEmpty is the following:

struct.size()==0

So it’s obvious, that there is no difference in performance.

Like
2019-03-08 10:46:34
2019-03-08 10:46:34

I assume that the implementation of StructIsEmpty is the following:struct.size()==0So it’s obvious, that there is no difference in performance.

Like
Add Comment