我是编译型编程语言的忠实粉丝,一直都是。虽然解释型编程语言允许开发人员更快地编写和测试代码,但我仍然认为编译器值得长期投资。在我看来,编译代码有两个明显的优势:可以验证对代码的每一次修改,甚至在代码开始运行之前。更快的执行速度。根据具体情况,代码可能会被编译为非常低级的执行指令。之所以要写这篇文章,是想比较一下编译型代码的执行速度比解释型代码快多少。由于我偏爱编译型编程语言,这里有一个问题:我有很多有趣的代码,但都是用Python编写的,我该怎么办?重写所有?部分重写?完全不重写?先入之见在这篇文章中,我通过比较它们在不同任务上的表现来检验我对Java、Go和Python的一些先入之见。首先是Python,我正在考虑更换它。至于Java,我已经成为它的粉丝20多年了,看着它在性能和功能方面不断成熟和完善。最后是Go,我两年前才开始使用它,但真的很喜欢它。Go虽然相比Java少了一些特性,比如类继承,但是它的语法简洁紧凑,编译和执行速度很快,生成的代码也非常紧凑,并且还提供了优雅的goroutines用于并发处理。以下是我的一些先入之见。编译代码的执行速度比解释代码快一个数量级。早些时候,当我比较使用和不使用JIT编译的Java代码的性能时,比率约为30比1。Go运行速度比Java快一点。我记得在我以前的工作中做过一些测试,发现Go在某些任务上比Java快30%,但最近的一些文章说Java比Go快。我们先测试一下。我在之前的文章中通过一些代码对比了JIT的性能,然后又用Python和Go实现了。这段代码计算100的斐波那契值,每轮50次,并以纳秒为单位打印执行时间,总共200轮。可以在https://github.com/rodrigoramirez/fibonacci找到代码。三种语言的输出结果看起来像这样:JavaGoPython...122123116831191071153912310411358120115119261191181197312010411377109103129601271221568311210611482...平均值是这样:JavaGoPython13010510050可以看到,在计算Fibonacci数值时,Java比Go要慢一些,大概慢24%,而Python几乎That's100timesslower,or9458%.ThisresultconfirmedmyinitialjudgmentaboutJavaandGo,butwhatsurprisedmewastheperformanceofPython,whichwasnotjustanorderofmagnitudeslower,buttwo!I'mwonderingwhyPythonistakingsomuchtime.MyfirstthoughtisthatalotofpeoplefocusontheeaseofuseofPythonandsacrificeperformancetogetfastresults.Ibelievealldatascientiststhinkthisway.Besides,therearesomanyready-madelibrariesavailable,whylookforothers?Soonerorlatersomeonewilloptimizethem.Thesecondreasonisthatmanypeoplehavenotcompareddifferentimplementations,becausemanystart-upcompaniesarebusymakingproductsinthefiercecompetition,andhavenotimetoconsiderwhethertooptimizeornot.Thirdreason,therearewaystomakethesamePythoncoderunfaster.WhataboutcompilingthePythoncode?Afterdoingsomeresearch,IdecidedtotestthesamePythoncodeusingPyPy.PyPyisanotherimplementationofPythonthatitselfisdevelopedinPythonandincludesaJITcompilerlikeJava.LikeJava,weneedtoignoretheinitialoutputandskiptheJITcompilationprocess,andherearetheresults:JavaGoPythonPyPy130105100501887PyPyrespondsonaverage5timesfasterthanPython,butstill20timesslowerthanGo.MoretestsTheabovetestsmainlyfocusonthecalculationofvalues.IfIgobacktothePythoncodementionedatthebeginning,Ialsoneedtopayattentionto:IOofKafka,HTTPlisteneranddatabase;parsingJSONmessages.SummaryThisarticleperformedsimplemathtoconcludethatGoexecutessomewhatfasterthanJava,and2ordersofmagnitudefasterthaninterpretedPython.Basedonsuchresults,IpersonallywouldnotuseGotoreplaceJava.另一方面,在高负载、关键任务环境中使用Python并不是一个好的选择。如果您遇到这种情况,请考虑使用Python编译器作为短期解决方法。在决定是否重写Python代码时,还有其他因素需要考虑,例如IO和CPU问题,但这些超出了本文的范围。有人提醒我,在Go和Java中使用64位整数只能准确计算出92的斐波那契值,然后就会出现溢出(译者:所以后来改代码计算90的斐波那契值)。但即便如此,本文的结论仍然有效。
