Запуск Javascript извлечение занимает около 60 мс на вызов на моем аппарате. По сравнению с Python запросами в 3 мс, это намного медленнее.
Вопросы
- Почему
fetch
намного медленнее? - Есть ли способ ускорить его? Я в порядке с ответами, которые требуют, чтобы я перенастроил свой браузер.
Эксперимент
Это детали моего эксперимента.
Система
- Браузер: Firefox 74.0 (64-разрядная версия)
- Операционная система: Ubuntu 18.04.4 LTS
- Сервер: Django 3.0.3 (но с * 1028) * намного быстрее, это не должно иметь значения). Сервер и клиент находятся на одном компьютере.
- Для
requests
: Python 3.7.6 с requests
2.23.0 - Процессор: Intel (R) Core (TM) i5 -6600K CPU @ 3,50 ГГц
Javascript Fetch
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();
Firefox вывод консоли на страницу HTML:
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