Tải bản đầy đủ - 0 (trang)
Chapter 8.  Don't optimize prematurely

Chapter 8.  Don't optimize prematurely

Tải bản đầy đủ - 0trang

Summary

Spurnotawillinghorse(Latinproverb):Prematureoptimization

isasaddictiveasitisunproductive.Thefirstruleof

optimizationis:Don'tdoit.Thesecondruleofoptimization(for

expertsonly)is:Don'tdoityet.Measuretwice,optimizeonce.



Discussion

As[Stroustrup00]Đ6'sintroductionquotessodeliciously:

Prematureoptimizationistherootofallevil.

DonaldKnuth[quotingHoare]

Ontheotherhand,wecannotignoreefficiency.

JonBentley

HoareandKnuthare,ofcourseandasalways,completely

correct(seeItem6andthisItem).SoisBentley(seeItem9).

Wedefineprematureoptimizationasmakingdesignsorcode

morecomplex,andsolessreadable,inthenameof

performancewhentheeffortisnotjustifiedbyaproven

performanceneed(suchasactualmeasurementand

comparisonagainstgoals)andthusbydefinitionaddsno

provenvaluetoyourprogram.Alltoooften,unneededand

unmeasuredoptimizationeffortsdon'tevenmaketheprogram

anyfaster.

Alwaysremember:

Itisfar,fareasiertomakeacorrectprogramfast

thanitistomakeafastprogramcorrect.

So,bydefault,don'tfocusonmakingcodefast;focusfirston

makingcodeasclearandreadableaspossible(seeItem6).

Clearcodeiseasiertowritecorrectly,easiertounderstand,

easiertorefactorandeasiertooptimize.Complications,

includingoptimizations,canalwaysbeintroducedlaterandonly

ifnecessary.



Therearetwomajorreasonswhyprematureoptimizations

frequentlydon'tevenmaketheprogramfaster.First,we

programmersarenotoriouslybadatestimatingwhatcodewill

befasterorsmaller,andwherethebottlenecksinourcodewill

be.Thisincludestheauthorsofthisbook,anditincludesyou.

Consider:Moderncomputersfeatureanextremelycomplex

computationalmodel,oftenwithseveralpipelinedprocessing

unitsworkinginparallel,adeepcachehierarchy,speculative

execution,branchpredictionandthat'sjusttheCPUchip.On

topofthehardware,compilerstaketheirbestguessat

transformingyoursourcecodeintomachinecodethatexploits

thehardwareatitsbest.Andontopofallthatcomplication,

it'swell,it'syourguess.Soifyougowithnothingbut

guesswork,thereislittlechanceyourill-targetedmicrooptimizationswillsignificantlyimprovethings.So,optimization

mustbeprecededbymeasurement;andmeasurementmustbe

precededbyoptimizationgoals.Untiltheneedisproven,your

focusshouldbeonpriority#1writingcodeforhumans.(When

someoneasksyoutooptimize,dodemandproof.)

Second,inmodernprograms,increasinglymanyoperations

aren'tCPU-boundanyway.Theymaybememory-bound,

network-bound,disk-bound,waitingonawebservice,or

waitingonadatabase.Atbest,tuningapplicationcodeinsuch

operationsonlymaketheoperationswaitfaster.Italsomeans

thattheprogrammerwastedvaluabletimeimprovingwhat

didn'tneedimprovinginsteadofaddingvaluebyimproving

whatdid.

Ofcourse,thedaywillcomewhenyoudoneedtooptimize

somecode.Whenyoudoso,lookfirstforanalgorithmic

optimization(seeItem7)andtrytoencapsulateand

modularizetheoptimization(e.g.,inafunctionorclass;see

Items5and11),andclearlystateinacommentthereasonof

theoptimizationandareferencetothealgorithmused.

Acommonbeginner'smistakeistowritenewcodewhile

obsessingwithpride!overoptimalexecutionatthecostof



understandability.Moreoftenthannot,thisyieldsmilesof

spaghettithat,evenifcorrectinthebeginning,ishardtoread

andchange.(SeeItem6.)

Itisnotprematureoptimizationtopassbyreference(seeItem

25),toprefercallingprefix++and--(seeItem28),anduse

similaridiomsthatshouldjustnaturallyflowoutofour

fingertips.Thesearenotprematureoptimizations;theyare

simplyavoidingprematurepessimizations(seeItem9).



Examples

Example:Aninlineirony.Hereisasimpledemonstrationof

thehiddencostofaprematuremicro-optimization:Profilersare

excellentattellingyou,byfunctionhitcount,whatfunctions

youshouldhavemarkedinlinebutdidn't;profilersareterrible

attellingyouwhatfunctionsyoudidmarkinlinebutshouldn't

have.Toomanyprogrammers"inlinebydefault"inthenameof

optimization,nearlyalwaystradinghighercouplingforatbest

dubiousbenefit.(Thisassumesthatwritinginlineeven

mattersonyourcompiler.See[Sutter00],[Sutter02],and

[Sutter04].)



Exceptions

Whenwritinglibraries,it'shardertopredictwhatoperationswill

endupbeingusedinperformance-sensitivecode.Buteven

libraryauthorsrunperformancetestsagainstabroadrangeof

clientcodebeforecommittingtoobfuscatingoptimizations.



References

[Bentley00]Đ6[Cline99]Đ13.01-09[Kernighan99]Đ7

[Lakos96]Đ9.1.14[Meyers97]Đ33[Murray93]Đ9.9-10,

Đ9.13[Stroustrup00]Đ6introduction[Sutter00]Đ30,Đ46

[Sutter02]Đ12[Sutter04]Đ25



9.Don'tpessimizeprematurely

Summary

Discussion

References



Summary

Easyonyourself,easyonthecode:Allotherthingsbeing

equal,notablycodecomplexityandreadability,certainefficient

designpatternsandcodingidiomsshouldjustflownaturally

fromyourfingertipsandarenohardertowritethanthe

pessimizedalternatives.Thisisnotprematureoptimization;itis

avoidinggratuitouspessimization.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 8.  Don't optimize prematurely

Tải bản đầy đủ ngay(0 tr)

×