Table of Contents
Question content
Solution
Home Backend Development Golang Understand pointer operations and CPU/memory usage

Understand pointer operations and CPU/memory usage

Feb 08, 2024 pm 10:20 PM

了解指针操作和 CPU/内存使用情况

php editor Banana will introduce you to pointer operations and CPU/memory usage. In programming, pointer manipulation is a powerful tool that can directly access and modify data in memory. By understanding pointer operations, you can better control and optimize the performance of your code. In addition, understanding CPU and memory usage is also very important for optimizing programs. By monitoring and analyzing CPU and memory usage, you can identify potential performance issues and take appropriate measures to improve program operation efficiency. In this article, we will introduce you to the relevant knowledge of pointer operations and CPU/memory usage in detail to help you better understand and apply them.

Question content

I was discussing with a colleague at work whether it would be more efficient to pass a pointer to a function and/or return a pointer.

I've put together some benchmark functions to test different ways of doing this. These functions basically take a variable, convert it and pass it back. We have 4 different methods:

  1. Pass in the variable normally, create a new variable for the conversion result and pass back a copy of it
  2. Pass in the variable normally, create a new variable for the conversion result, and return the memory address
  3. Pass in a pointer to a variable, create a new variable for the conversion result and return a copy of the variable
  4. Pass in a pointer to a variable and convert the value of the pointer without returning anything.
package main

import (
    "fmt"
    "testing"
)

type mystruct struct {
    mystring string
}

func acceptparamreturnvariable(s mystruct) mystruct {
    ns := mystruct{
        fmt.sprintf("i'm quoting this: \"%s\"", s.mystring),
    }
    return ns
}

func acceptparamreturnpointer(s mystruct) *mystruct {
    ns := mystruct{
        fmt.sprintf("i'm quoting this: \"%s\"", s.mystring),
    }
    return &ns
}

func acceptpointerparamreturnvariable(s *mystruct) mystruct {
    ns := mystruct{
        fmt.sprintf("i'm quoting this: \"%s\"", s.mystring),
    }
    return ns
}

func acceptpointerparamnoreturn(s *mystruct) {
    s.mystring = fmt.sprintf("i'm quoting this: \"%s\"", s.mystring)
}

func benchmarknormalparamreturnvariable(b *testing.b) {
    s := mystruct{
        mystring: "hello world",
    }
    var ns mystruct
    for i := 0; i < b.n; i++ {
        ns = acceptparamreturnvariable(s)
    }
    _ = ns
}

func benchmarknormalparamreturnpointer(b *testing.b) {
    s := mystruct{
        mystring: "hello world",
    }
    var ns *mystruct
    for i := 0; i < b.n; i++ {
        ns = acceptparamreturnpointer(s)
    }
    _ = ns
}

func benchmarkpointerparamreturnvariable(b *testing.b) {
    s := mystruct{
        mystring: "hello world",
    }
    var ns mystruct
    for i := 0; i < b.n; i++ {
        ns = acceptpointerparamreturnvariable(&s)
    }
    _ = ns
}

func benchmarkpointerparamnoreturn(b *testing.b) {
    s := mystruct{
        mystring: "hello world",
    }
    for i := 0; i < b.n; i++ {
        acceptpointerparamnoreturn(&s)
    }
    _ = s
}
Copy after login

I found the results quite surprising.

$ go test -run=XXXX -bench=. -benchmem
goos: darwin
goarch: amd64
pkg: XXXX
cpu: Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
BenchmarkNormalParamReturnVariable-16           10538138               103.3 ns/op            48 B/op          2 allocs/op
BenchmarkNormalParamReturnPointer-16             9526380               201.2 ns/op            64 B/op          3 allocs/op
BenchmarkPointerParamReturnVariable-16           7542066               147.0 ns/op            48 B/op          2 allocs/op
BenchmarkPointerParamNoReturn-16                   45897            119265 ns/op          924351 B/op          5 allocs/op
Copy after login

Before running this, I thought the most efficient way would be the fourth test, since no new variables are created within the scope of the function being called and only the memory address is passed, however, it seems that the fourth is efficient The one with the lowest takes the most time and uses the most memory.

Can someone explain this to me, or provide me with some good reading links that explain this?

Solution

The benchmark you did does not answer the question you asked. It turns out that microbenchmarking is extremely difficult - not just in the go world, but in general.

Back to the issue of efficiency. Normally, passing pointers to functions is not escaped to the heap. Normally, pointers returned from functions do escape to the heap. Usually is the key word here. You can't really tell when the compiler allocates something on the stack and when it allocates something on the heap. This is no small problem. A very good short explanation can be found here.

But if you need to know, you can ask. You can start by simply printing the optimization decisions made by the compiler. You can do this by passing the m flag to the go tool compile.

go build -gcflags -m=1
Copy after login

If you pass an integer greater than 1, you will get more verbose output. If it doesn't give you the answers you need to optimize your program, try Analysis. It goes far beyond memory analysis.

In general, don’t worry about naive optimization decisions in your daily work. Don't get too hung up on "usually..." because in the real world, you never know. Always aim for correctness optimization first. Then only optimize for performance if you really need it and prove you need it. Don't guess, don't believe. Also, keep in mind that go is changing, so what we prove in one version won't necessarily hold true in another.

The above is the detailed content of Understand pointer operations and CPU/memory usage. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go language pack import: What is the difference between underscore and without underscore? Go language pack import: What is the difference between underscore and without underscore? Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import &quot;fmt&quot;) and blank imports (e.g., import _ &quot;fmt&quot;). Named imports make package contents accessible, while blank imports only execute t

How to convert MySQL query result List into a custom structure slice in Go language? How to convert MySQL query result List into a custom structure slice in Go language? Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How to implement short-term information transfer between pages in the Beego framework? How to implement short-term information transfer between pages in the Beego framework? Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How to write files in Go language conveniently? How to write files in Go language conveniently? Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles