« MBS Xojo Plugins, ver… | Home | MBS Xojo Plugins, ver… »

Tip of the day: Avoid repeated variant packaging

If you work a lot with variants, you may more often than needed, create or destroy variants on the way, often without noticing. Not every developer knows that assigning something to CellTag() or adding something to dictionary may create a new variant object. If you know the little details, you may notice it.

If you have a dictionary with strings as keys and values, you may have a loop like this:

for each key as string in dic.keys dim value as string = dic.Value(key) System.DebugLog "key: "+value next

What do you don’t see is the implicit conversions happening. For each step of the loop, the key is queried as variant. Since a string is needed, the StringValue function gets called to get the string value of the variant. If this is a variant containing a string, this is just a reference count +1 and returning the string. But if this is a number, it will call a ToString function internally and create a new string here.

Next you have the dic.value() lookup, which takes a variant. We pass the string for the key and since Value() needs a variant, a new variant is created. Like a hidden line calling „new“ with „VariantString“ class (or whatever it is called internally). This may look like this:

for each tempKey as variant in dic.keys dim key as string = tempKey.StringValue dim tempKey2 as Variant = new VariantString(key) dim value as string = dic.Value(tempKey2) System.DebugLog "key: "+value next

Of course that is pseudo code and not actually what happens. But still you see that we read a variant and create a new one to have it read by Value() function. Let’s solve this with code like this:

for each keyVariant as variant in dic.keys dim key as string = keyVariant dim value as string = dic.Value(keyVariant) System.DebugLog "key: "+value next

Now we loop with variant, so no need to construct a temporary one later for Value(). If you benchmark this, you should see a nice speed improvement.

The biggest plugin in space...
09 11 21 - 10:58