AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79560227
Accepted
Pavel Chersky
Pavel Chersky
Asked: 2025-04-07 23:08:12 +0800 CST2025-04-07 23:08:12 +0800 CST 2025-04-07 23:08:12 +0800 CST

使用“一次分配”实现二维切片的效率如何?

  • 772

我正在学习 Go,现在开始研究数组和切片。我参考了《Effective Go》和《A Tour of Go》。我对切片容量的计算公式有些疑问。请参阅下面代码中的注释。

package main

import "fmt"

func main() {

    // let's say I need to implement 5x5 picture with 2D slice
    // and I have two ways to do that in acc. with
    // https://go.dev/doc/effective_go#two_dimensional_slices

    // that said:
    // 1. six slices - six underlying arrays
    picture := make([][]uint8, 5)
    for i := range picture {
        picture[i] = make([]uint8, 5)
    }

    // 2. six slices - two* underlying arrays
    // *I THOUGHT the efficiency is hiding in number of arrays
    picture = make([][]uint8, 5)
    pixels := make([]uint8, 25)
    for i := range picture {
        // every iteration pixels[5:] allocates new array...
        picture[i], pixels = pixels[:5], pixels[5:]
        // ...but in the new iteration it's deleted
        // leaving slice of initial pixels array in picture[i]...
    }
    // ...and here we have only two arrays...
    // ...         ^^^ B5t ^^^

    // there are six arrays anyway
    // but their capacity is 5 for picture and
    // 25, 20...5 respectively for its contents
    fmt.Print(cap(picture), " ")
    for i := range picture {
        fmt.Print(cap(picture[i]), " ")
    }
    fmt.Println()
    // if you don't understand let me explain my position
    // capacity is characteristic of underlying array rather than
    // of slice itself

    // in acc. with https://go.dev/tour/moretypes/11
    // "The capacity of a slice is the number of
    // elements in the underlying array..."

    // I believe that capacity of array is immutable one and
    // one array cannot have different cap's at the same time

    picture = make([][]uint8, 5)
    for i := range picture {
        picture[i] = make([]uint8, 5)
    }

    // here we have six arrays but capacity of each is 5
    // so the first solution works efficiently than second one
    //                  I believe
    fmt.Print(cap(picture), " ")
    for i := range picture {
        fmt.Print(cap(picture[i]), " ")
    }
    fmt.Println()

}

该代码的输出是:

5 25 20 15 10 5 
5 5 5 5 5 5 

有人可以解释一下使用一种分配方法的效率隐藏在哪里吗?

arrays
  • 1 1 个回答
  • 94 Views

1 个回答

  • Voted
  1. Best Answer
    rocka2q
    2025-04-08T06:59:15+08:002025-04-08T06:59:15+08:00

    第二个有效 Go二维切片示例是在完整切片表达式添加到Go 编程语言规范之前创建的。

    one allocation, sliced into lines:
    
    // Allocate the top-level slice, the same as before.
    picture := make([][]uint8, YSize) // One row per unit of y.
    // Allocate one large slice to hold all the pixels.
    pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8.
    // Loop over the rows, slicing each row from the front of the remaining pixels slice.
    for i := range picture {
        picture[i], pixels = pixels[:XSize], pixels[XSize:]
    

    第二个例子应为:

    one allocation, sliced into lines:
    
    // Allocate the top-level slice, the same as before.
    picture := make([][]uint8, YSize) // One row per unit of y.
    // Allocate one large slice to hold all the pixels.
    pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8.
    // Loop over the rows, slicing each row from the front of the remaining pixels slice.
    for i := range picture {
        // Use a full slice expression for the correct row capacity
        picture[i], pixels = pixels[:XSize:XSize], pixels[XSize:]
    }
    

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        XSize, YSize := 5, 5
    
        // Effective Go: Two-dimensional slices
        // https://go.dev/doc/effective_go#two_dimensional_slices
        // one allocation, sliced into lines:
        // Allocate the top-level slice, the same as before.
        picture := make([][]uint8, YSize) // One row per unit of y.
        // Allocate one large slice to hold all the pixels.
        pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8.
        // Loop over the rows, slicing each row from the front of the remaining pixels slice.
        for i := range picture {
            // Use a full slice expression for the correct row capacity
            // https://go.dev/ref/spec#Slice_expressions
            picture[i], pixels = pixels[:XSize:XSize], pixels[XSize:]
        }
    
        fmt.Print(cap(picture), " ")
        for i := range picture {
            fmt.Print(cap(picture[i]), " ")
        }
        fmt.Println()
    }
    

    https://go.dev/play/p/7I2ZL5Jj8Lw。

    输出:

    5 5 5 5 5 5
    

    一个简单的Go 基准测试说明了最小化分配的一些效果。

    Benchmark1stExample-16  6710131  175.6 ns/op  154 B/op  6 allocs/op
    Benchmark2ndExample-16  9674449  121.3 ns/op  160 B/op  2 allocs/op
    
    • 1

相关问题

  • 可以从指针数组中的值初始化指针吗?

  • 可以初始化指向类型变量数组的指针吗?

  • Swift Array,如何从数组中检索嵌套枚举中的所有元素

  • 为什么 C 字符串并不总是等同于字符数组?

  • PowerShell:如何像这样转换 hastable 数组值?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve