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!

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
