婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > Golang 空map和未初始化map的注意事項說明

Golang 空map和未初始化map的注意事項說明

熱門標簽:百度地圖標注后傳給手機 壽光微信地圖標注 阿克蘇地圖標注 涿州代理外呼系統 評價高的400電話辦理 電話機器人軟件免費 外呼系統顯本地手機號 excel地圖標注分布數據 外呼系統用什么卡

可以對未初始化的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去刪除所有元素。如下:

再來看看關閉優化后的結果:

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

關閉優化選項后,Go編譯器直接通過循環遍歷來刪除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.flagshashWriting != 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.flagshashWriting == 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)
		}
	}
}

得到測試結果如下:

從測試結果上看,好像確實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)
}

測試結果如下:

從測試結果上看,好像確實是make方式的效率更低,而且內存占用更多,但結果真的是這樣嗎?

我們把make方式的make map的大小改為0再試一下:

tmpMap = make(map[string]string)

得到如下結果,What?時間為0了,內存消耗也跟delete的方式一樣:

我們把make方式的make map的大小改為10000再試一下:

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

結果如下:

三、總結

通過上面的測試,可以得出結論:

1、在map的數量級在10w以內的話,make方式會比delete方式速度更快,但是內存會消耗更多一點。

2、如果map數量級大于10w的話,delete的速度會更快,且內存消耗更少。

3、對于不再使用的map,直接使用make方式,長度為0清空更快。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • golang 實現對Map進行鍵值自定義排序
  • golang 如何獲取map所有key的方式
  • golang判斷key是否在map中的代碼
  • 解決Golang map range遍歷結果不穩定問題
  • 快速解決Golang Map 并發讀寫安全的問題
  • golang 實現struct、json、map互相轉化
  • Golang自定義結構體轉map的操作
  • Golang 使用Map實現去重與set的功能操作

標簽:雞西 欽州 汕頭 梅河口 重慶 銅川 吐魯番 蘭州

巨人網絡通訊聲明:本文標題《Golang 空map和未初始化map的注意事項說明》,本文關鍵詞  Golang,空,map,和,未,初始化,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Golang 空map和未初始化map的注意事項說明》相關的同類信息!
  • 本頁收集關于Golang 空map和未初始化map的注意事項說明的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 漯河市| 梁河县| 三明市| 沽源县| 疏附县| 志丹县| 宽城| 金门县| 伊春市| 尖扎县| 安岳县| 修水县| 固镇县| 双城市| 三原县| 丘北县| 河西区| 健康| 绥化市| 内丘县| 阿勒泰市| 山阴县| 徐水县| 碌曲县| 乐山市| 安远县| 观塘区| 石台县| 文水县| 津市市| 广元市| 尚义县| 牡丹江市| 吐鲁番市| 靖州| 化隆| 静海县| 勐海县| 丰台区| 东辽县| 九寨沟县|