Golang 空map和未初始化map的注意事项说明

作者:菌菇 时间:2024-04-28 10:46:52 

可以对未初始化的map进行取值,但取出来的东西是空:


var m1 map[string]string
fmt.Println(m1["1"])

不能对未初始化的map进行赋值,这样将会抛出一个异常:

panic: assignment to entry in nil map


var m1 map[string]string
m1["1"] = "1"

通过fmt打印map时,空map和nil map结果是一样的,都为map[]。所以,这个时候别断定map是空还是nil,而应该通过map == nil来判断。

补充:Golang清空map的两种方式及性能比拼

一、Golang中删除map的方法

1、所有Go版本通用方法


a := make(map[string]int)
a["a"] = 1
a["b"] = 2
// clear all
a = make(map[string]int)

2. Go 1.11版本以上用法

通过Go的内部函数mapclear方法删除。这个函数并没有显示的调用方法,当你使用for循环遍历删除所有元素时,Go的编译器会优化成Go内部函数mapclear。


package main
func main() {
       m := make(map[byte]int)
       m[1] = 1
       m[2] = 2
       for k := range m {
       delete(m, k)
       }
}

把上述源代码直接编译成汇编(默认编译是会优化的):


go tool compile -S map_clear.go

可以看到编译器把源码9行的for循环直接优化成了mapclear去删除所有元素。如下:

Golang 空map和未初始化map的注意事项说明

再来看看关闭优化后的结果:


go tool compile -l -N -S map_clear.go

关闭优化选项后,Go编译器直接通过循环遍历来删除map里面的元素。

Golang 空map和未初始化map的注意事项说明

具体的mapclear代码可以在go源码库中runtime/map.go文件中看到,代码如下:


// mapclear deletes all keys from a map.
func mapclear(t *maptype, h *hmap) {
if raceenabled && h != nil {
callerpc := getcallerpc()
pc := funcPC(mapclear)
racewritepc(unsafe.Pointer(h), callerpc, pc)
}
if h == nil || h.count == 0 {
return
}
if h.flags&hashWriting != 0 {
throw("concurrent map writes")
}
h.flags ^= hashWriting
h.flags &^= sameSizeGrow
h.oldbuckets = nil
h.nevacuate = 0
h.noverflow = 0
h.count = 0
// Keep the mapextra allocation but clear any extra information.
if h.extra != nil {
*h.extra = mapextra{}
}
// makeBucketArray clears the memory pointed to by h.buckets
// and recovers any overflow buckets by generating them
// as if h.buckets was newly alloced.
_, nextOverflow := makeBucketArray(t, h.B, h.buckets)
if nextOverflow != nil {
// If overflow buckets are created then h.extra
// will have been allocated during initial bucket creation.
h.extra.nextOverflow = nextOverflow
}
if h.flags&hashWriting == 0 {
throw("concurrent map writes")
}
h.flags &^= hashWriting
}

二、两种清空map方式性能比较

1、先用benchmark的方式测一下两种方式

benchmark代码如下:


func BenchmarkMakeNewMap(b *testing.B) {
tmpMap := make(map[string]string, 10000)
for i := 0; i < b.N; i++ {
for j := 0; j < 10000; j++ {
tmpMap["tmp"+strconv.Itoa(j)] = "tmp"
}
tmpMap = make(map[string]string, 10000)
}
}
func BenchmarkDeleteMap(b *testing.B) {
tmpMap := make(map[string]string, 10000)
for i := 0; i < b.N; i++ {
for j := 0; j < 10000; j++ {
tmpMap["tmp"+strconv.Itoa(j)] = "tmp"
}
for k := range tmpMap {
delete(tmpMap, k)
}
}
}

得到测试结果如下:

Golang 空map和未初始化map的注意事项说明

从测试结果上看,好像确实delete的方式效率更高,但是这个benchmark中总感觉没有测试到真正清空map的地方,中间穿插着put map的操作,我们用方法2再测一下。

2、单个UT测一下两种方式

UT代码如下:

测试过程中禁用了gc,避免gc对运行时间和内存产生干扰。


func TestMakeNewMap(t *testing.T) {
  debug.SetGCPercent(-1)
  var m runtime.MemStats
  tmpMap := make(map[string]string, 1000000)
  for j := 0; j < 1000000; j++ {
     tmpMap["tmp"+strconv.Itoa(j)] = "tmp"
  }
  start := time.Now()
  tmpMap = make(map[string]string, 1000000)
  fmt.Println(time.Since(start).Microseconds())
  runtime.ReadMemStats(&m)
  fmt.Printf("%d Kb\n", m.Alloc/1024)
}
func TestDeleteMap(t *testing.T) {
  debug.SetGCPercent(-1)
  var m runtime.MemStats
  tmpMap2 := make(map[string]string, 1000000)
  for j := 0; j < 1000000; j++ {
     tmpMap2["tmp"+strconv.Itoa(j)] = "tmp"
  }
  start := time.Now()
  for k := range tmpMap2 {
     delete(tmpMap2, k)
  }
  fmt.Println(time.Since(start).Microseconds())
  runtime.ReadMemStats(&m)
  fmt.Printf("%d Kb\n", m.Alloc/1024)
}

测试结果如下:

Golang 空map和未初始化map的注意事项说明

从测试结果上看,好像确实是make方式的效率更低,而且内存占用更多,但结果真的是这样吗?

我们把make方式的make map的大小改为0再试一下:


tmpMap = make(map[string]string)

得到如下结果,What?时间为0了,内存消耗也跟delete的方式一样:

Golang 空map和未初始化map的注意事项说明

我们把make方式的make map的大小改为10000再试一下:


tmpMap = make(map[string]string, 10000)

结果如下:

Golang 空map和未初始化map的注意事项说明

三、总结

通过上面的测试,可以得出结论:

1、在map的数量级在10w以内的话,make方式会比delete方式速度更快,但是内存会消耗更多一点。

2、如果map数量级大于10w的话,delete的速度会更快,且内存消耗更少。

3、对于不再使用的map,直接使用make方式,长度为0清空更快。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持asp之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/qq_39920531/article/details/88103496

标签:Golang,初始化,map
0
投稿

猜你喜欢

  • 从Python的源码来解析Python下的freeblock

    2023-07-26 20:44:39
  • Python制作简易注册登录系统

    2022-08-25 14:46:28
  • PHP实现网页内容html标签补全和过滤的方法小结【2种方法】

    2023-09-06 22:28:26
  • JavaScript DOM节点操作方法总结

    2024-04-16 09:24:36
  • perl 文件操作总结

    2023-07-07 07:17:38
  • MySQL存储引擎简介及MyISAM和InnoDB的区别

    2024-01-26 23:53:17
  • php Exception异常处理详解

    2023-05-29 21:51:37
  • Go语言中日期包(time包)的具体使用

    2024-05-08 10:52:33
  • 微信小程序实现横向滚动导航栏效果

    2024-04-29 13:55:49
  • Python实现将Excel转换成xml的方法示例

    2023-01-19 23:02:53
  • JavaScript体验异步更好的解决办法

    2024-05-29 22:11:56
  • Python3常见函数range()用法详解

    2021-04-20 10:34:19
  • python3.6.4安装opencv3.4.2的实现

    2021-08-07 22:48:56
  • python 邮件检测工具mmpi的使用

    2022-03-18 04:56:45
  • C#使用Oracle.ManagedDataAccess.dll组件连接Oracle数据库

    2024-01-27 23:55:45
  • JS数组Array常用方法汇总+实例

    2024-04-30 10:42:02
  • 如何用Python破解wifi密码过程详解

    2021-06-03 05:32:38
  • Django 报错:Broken pipe from ('127.0.0.1', 58924)的解决

    2021-03-27 21:12:09
  • 修改mysql最大连接数的方法

    2010-03-09 13:57:00
  • Python使用UDP实现720p视频传输的操作

    2023-12-04 09:32:49
  • asp之家 网络编程 m.aspxhome.com