Javascript 获取速度慢(60 毫秒对 3 毫秒)

Javascript Fetch is Slow (60ms vs 3ms)

运行 Javascript fetch takes about 60ms per call on my machine. Compared to Python requests 3ms,这个慢多了。

问题


实验

这些是我实验的细节。

系统

Javascript 获取

HTML 运行下面的 Javascript:

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>
  <body>
  </body>
</html>

Javascript 发出多个 fetch 请求并报告每个请求的平均时间。

// record all times
const times = [];

function call() {
    // record starting time
    const startFetch = performance.now();
    fetch("http://127.0.0.1:8000/timer/time")
        .then((response) => {
            // compute fetch duration
            const elapsedFetch = performance.now() - startFetch;

            // record result
            console.log(elapsedFetch);
            times.push(elapsedFetch);

            if (times.length<100) {
                // start next call
                call();
            } else {
                // report statistics
                const totalFetch = times.reduce((a, b) => a + b, 0);
                const averageFetch = totalFetch/times.length;
                const standardDeviation = Math.sqrt(times.reduce((a, b) => a + (b-averageFetch) ** 2, 0)/times.length);
                const totalElapsed = performance.now() - startTime;
                console.log("Average fetch time:", averageFetch, '+-', standardDeviation);
                console.log("Percentage of overall elapsed:", totalFetch/totalElapsed)
            }
        });
}

var startTime = performance.now();
call();

访问 HTML 页面时 Firefox 控制台输出:

Average fetch time: 62.51 +- 31.450117646838777
Percentage of overall elapsed: 0.9993605115907274

Google Chrome 版本 80.0.3987.149(官方构建)(64 位)的类似结果

Average fetch time: 49.93 +- 4.92596183501253
Percentage of overall elapsed: 0.9993995196156925

使用 XMLHttpRequest 代替 fetch:

xhr.open("GET", "http://127.0.0.1:8000/timer/time");
xhr.send();
xhr.onload = ...

产生相似的结果:

Average fetch time: 60.19 +- 26.325157169521326
Percentage of overall elapsed: 0.9993358791300017

Python 请求

代码类似于 Javascript,但在 Python 中:

import requests
import time
import numpy as np

times = []
start_time = time.time()

for i in range(100):
    start_get = time.time()
    response = requests.get('http://127.0.0.1:8000/timer/time')
    elapsed_get = time.time() - start_get
    times += [elapsed_get]

total_elapsed = time.time() - start_time

total_get = np.sum(times)
average_get = np.average(times)
standard_deviation = np.std(times)

print("Average get time:", average_get, '+-', standard_deviation)
print("Percentage of overall elapsed:", total_get/total_elapsed)

输出:

Average get time: 0.0025661182403564453 +- 0.0001961814487345112
Percentage of overall elapsed: 0.9994576986364464

虽然我仍然不知道为什么 Javascript 获取如此慢,但我已经能够切换到更快的选项:

我现在使用 WebSockets (on the client) and Django Channels(在服务器上),速度明显更快。