我有一个大文件(无法完全放入内存),其中包含各种大小的字符串。我想将这些字符串重写到另一个文件中,但每个字符串都大写。在 go 中实现这一目标的最快方法是什么?
这是我能想到的最有效的方法。关于如何使其更快的任何想法?
package main import ( "bufio" "log" "os" "strings" ) func main() { inputFile, err := os.Open("input.txt") if err != nil { log.Fatal(err) } defer inputFile.Close() outputFile, err := os.Create("output.txt") if err != nil { log.Fatal(err) } defer outputFile.Close() scanner := bufio.NewScanner(inputFile) writer := bufio.NewWriter(outputFile) for scanner.Scan() { line := scanner.Text() capitalized := strings.ToUpper(line) _, err := writer.WriteString(capitalized + "\\n") if err != nil { log.Fatal(err) } } err = writer.Flush() if err != nil { log.Fatal(err) } }
正确答案
一个起点是运行 go 测试包 基准测试。
对于基准数据,我使用 275,502 个单词(大部分为小写)、3,077,701 字节的 linux 字典文件:/usr/share/dict/brazilian
。鉴于您对文件的模糊描述,这是我能做的最好的事情。为了避免基准磁盘 i/o,我对 io.reader 使用 bytes.reader,对 io.writer 使用 ioutil.discard。
代码的结果:
$ go test upper_so_test.go -run=! -benchmem -bench=. benchmarkso-12 48 22765120 ns/op 8143216 b/op 550993 allocs/op
blunderific 代码的结果:
benchmarkb-12 94 13061407 ns/op 3782866 b/op 275505 allocs/op
作为概念验证 (poc),我使用字典文件编写了使用最少 cpu 和内存的代码。到目前为止,我的 poc 代码的结果:
benchmarktu-12 182 6457334 ns/op 8240 b/op 3 allocs/op
将我的 poc 代码作为程序运行,使用 ssd 文件存储来读取和写入字典文件,需要几毫秒的时间:
$ time ./upper real 0m0.031s user 0m0.014s sys 0m0.009s
即使没有文件的一小部分样本,也无法提出性能改进的具体建议。然而,使用字典文件,我的 poc 基准测试结果与您的基准测试结果(6,457,334 ns/op vs. 22,765,120、8,240 b/op vs. 8,143,216、3 allocs/op vs. 550,993)确实表明您对 cpu 的过度使用内存会损害性能。
upper_so_test.go:
package main import ( "bufio" "bytes" "io" "io/ioutil" "os" "strings" "testing" ) func SOToUpper(r io.Reader, w io.Writer) error { scanner := bufio.NewScanner(r) writer := bufio.NewWriter(w) for scanner.Scan() { line := scanner.Text() capitalized := strings.ToUpper(line) _, err := writer.WriteString(capitalized + "\n") if err != nil { return err } } err := writer.Flush() if err != nil { return err } return nil } var benchData = func () []byte { data, err := os.ReadFile(`/usr/share/dict/brazilian`) if err != nil { panic(err) } return data }() func BenchmarkSO(b *testing.B) { for i := 0; i < b.N; i++ { r := bytes.NewReader(benchData) w := ioutil.Discard err := SOToUpper(r, w) if err != nil { b.Error(err) } } }
以上是用 go 重寫檔案最快的方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器