Why this performance decrease in keeping value variable in for range loop in go?

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?

Hi @ashTishad, welcome to the forum.

What do you mean by “faster than other submissions”?
Can you share benchmarks that show the performance of the two code snippets?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.