Jump to content

Recommended Posts

Posted

Hello all,

Is there a method within the For...In...Next loop that can give me the 'key' value of the Map datatype?

The iteration gives you the 'value' as standard, but I also need the 'Key'

I know I can extract all keys into a 1D array with MapKeys(), however I'm trying to avoid this as the function is called many times and potentially with large maps.

Global $mMap[]

For $x = 1 To 10
    $mMap["key" & $x] = $x
Next

For $iVal In $mMap

    ConsoleWrite("$iVal = " & $iVal & @CRLF)
    ;How to get 'Key' here?
    ;$sKey = $mMap.first

Next

Many thanks for your help

sjardz

Posted
Global $mMap[]

For $x = 1 To 2^16
    $mMap["key" & $x] = $x
Next
Global $hTimer = TimerInit()

Global $vVal

; ~278ms
For $sKey In MapKeys($mMap)
    $vVal = $mMap[$sKey]
Next

; ~790ms
;~ For $iVal In $mMap
;~  $vVal = $iVal
;~ Next


Global $fDeltaT = TimerDiff($hTimer)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : Delta Time=' & $fDeltaT & 'ms' & @CRLF)

also, iterating over the array from MapKeys this way is faster and you get the key :)

Posted

Hi Nine and Paw, many thanks for your input 👍.

The function that will be using this is called many times, so I was keen not to copy all the keys (as an array) to the heap every call, hence my avoidance of MapKeys().

I have a script that uses an array, I was wondering if a map would be more performant, but as Paw has demonstrated above, arrays are still faster in certain areas.

While re-writing to replace the array with a map I can across this problem with me implementation, was hoping there may be a hidden undocumented method to get the key.

Many thanks again for taking the time to look at this

Have a great 2024 🎉

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...