Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

Why is a Python Lambda wildly slower than a Javascript Lambda with the same functionality?

I am creating a sorting comparison workbench using AWS to host sorting lambdas.

I have a bubble sort algorithm implemented in python (python3.8) and javascript (nodejs12.x) lambdas. Both have 512MB memory allocated.

When I run these against eachother with array lengths N of 1 to 5500 I get the following graph. N is on the x axis and time taken in MS on the y axis:

Python Bubble Sort vs Javascript Bubble Sort

While I expect bubble sort to be slow, I didn't expect Python to be 100x slower compared with Javascript. The max milliseconds reached for JS is ~120, vs Python at ~11100.

Perhaps there is an AWS related explanation, or my implementation is very slow?

Update: I switched the runtime over from CPython to PyPy and this has reduced the time by x100 for running bubble sort, the graphs are now much closer together, thus the time difference was due to the compiler:

PyPy Bubble Sort vs Node Bubble Sort

question from:https://stackoverflow.com/questions/66053519/why-is-a-python-lambda-wildly-slower-than-a-javascript-lambda-with-the-same-func

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

cpython and node differ in how the code is interpreted:

  • Python (the standard cpython) is compiled to bytecode and then interpreted. So the interpreter spends most of it's time in a loop containing a big switch-case. (See https://github.com/python/cpython/blob/5f18c223391eef8c7d01241b51a7b2429609dd84/Python/ceval.c#L1622)

  • node.js (using V8) and PyPy use just in time compilation. This kind of Problem (tight loop, homogeneous types) is what JITs are best at: if the interpreter sees that some piece of code is run very often with the same types, the JIT generates and optimizes native code for it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...