Understand pointer operations and CPU/memory usage
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:
- Pass in the variable normally, create a new variable for the conversion result and pass back a copy of it
- Pass in the variable normally, create a new variable for the conversion result, and return the memory address
- Pass in a pointer to a variable, create a new variable for the conversion result and return a copy of the variable
- 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 }
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
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
