· Aug 22, 2018

Best way to initialize several variables

Hello Everyone,

I was wondering about the best way to initialize several variables, or several lists of variables.

Would it be better to write it like:

set (var1, var2, var3) = "value1"
set (var4, var5) = "value2"
set (var6,var7,var8) = "value3"


set var1="value1", var2="value1", var3="value1", var4="value2", var5="value2", var6="value3", var7="value3", var8="value3"


set var1 = "value1"
set var2 = "value1"
set var3 = "value1"
set var4 = "value2"
set var5 = "value2"
set var6 = "value3"
set var7 = "value3"
set var8 = "value3"

When comparing the speed of each methods:

 ClassMethod TestInitVariable(intNumberOfLoop As %String = 1000000)
  set TimeStart = $h
  for intI=0:1:intNumberOfLoop {
    set (aVar0,aVar1,aVar2,aVar3,aVar4)="Value1"
    set (aVar5,aVar6)="Value2"
    set (aVar7,aVar8,aVar9)="Value3"
  set TimeEnd = $h
  write "set (a,b)="""" ==> "_$system.SQL.DATEDIFF("ss",TimeStart,TimeEnd)_"s", !
  set TimeStart = $h
  for intI=0:1:intNumberOfLoop {
    set bVar0="Value1",bVar1="Value1",bVar2="Value1",bVar3="Value1",bVar4="Value1",bVar5="Value2",bVar6="Value2",bVar7="Value3",bVar8="Value3",bVar9="Value3"
  set TimeEnd = $h
  write "set a="""",b="""" ==> "_$system.SQL.DATEDIFF("ss",TimeStart,TimeEnd)_"s", !
  set TimeStart = $h
  for intI=0:1:intNumberOfLoop {
    set cVar0="Value1"
    set cVar1="Value1"
    set cVar2="Value1"
    set cVar3="Value1"
    set cVar4="Value1"
    set cVar5="Value2"
    set cVar6="Value2"
    set cVar7="Value3"
    set cVar8="Value3"
    set cVar9="Value3"
  set TimeEnd = $h
  write "set a="""" ... set b="""" ==> "_$system.SQL.DATEDIFF("ss",TimeStart,TimeEnd)_"s", !

It seems the second method is faster when having to iterate over hundred of millions of value:

> d ..TestInitVariable()
set (a,b)="" ==> 0s
set a="",b="" ==> 0s
set a="" ... set b="" ==> 1s

> d ..TestInitVariable(100000000)
set (a,b)="" ==> 28s
set a="",b="" ==> 19s
set a="" ... set b="" ==> 19s

What method are you using to initialize lists of variables and why? What is the best way for you (especially when inside iteration)?

Thank you for your comments and discussions.



Discussion (6)3
Log in or sign up to continue

In some cases I prefer the multiple set form for readability and maintainability, as it makes explicit that all of the variables should get the same value. With separate set commands, you could change one without changing the other.

It is known/expected that multiple set is slower than separate set commands, although you shouldn't see as big of a difference when the target is a global or a subscripted local.

You could also abuse set $listbuild for a task like this, although it's probably even slower:

s $lb(v1,v2,v3)=$lb("v1","v1","v2")

For benchmarking, you may want to use a high-precision timer like $zh, rather than $h.