I am kind of new to go language.While solving leetcode:two sum problem, i have noticed If I write for range loop like this, it says 97% faster than other submissions.
func twoSum(nums []int, target int) []int {
hMap := map[int]int{}
for i := range nums {
complement := target - nums[i]
_, ok := hMap[complement]
if ok == true {
return []int{i, hMap[complement]}
}
hMap[nums[i]] = i
}
return nil
}
But, with same algorithm and logic, If I write for range loop like this, it says 48% faster than other submissions.
func twoSum(nums []int, target int) []int {
hMap := map[int]int{}
for i , val := range nums {
complement := target - val
_, ok := hMap[complement]
if ok == true {
return []int{i, hMap[complement]}
}
hMap[val] = i
}
return nil
}
Why this performace decrease in keeping value variable in for range loop in go?