2

實測 HTTP/2 網頁加速效果

 2 years ago
source link: https://blog.darkthread.net/blog/http2-speed-test/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

實測 HTTP/2 網頁加速效果

2022-06-10 11:41 PM 0 740

gRPC 的高效能一大部分來自 HTTP/2,2015 發表至今,主流瀏覽器跟伺服器多已內建支援 HTTP/2,屬於成熟可用的技術。

我們都知道 HTTP/2 之所以速度快源自 Request/Response Multiplexing (多工傳輸)、Header 壓縮、Binary Framing Layer 及 Server Push (延伸閱讀:Http/2 是什麼? by Po-Ching Lu),網路上的介紹很多,但很少看到有人實地驗證換用 HTTP/2 真的變快的效果,出於好奇,我想實測一下,眼見為憑。

我認為 Request/Reseponse Multiplexing 是變快最大的關鍵,HTTP/1.x 具有 Domain Sharding 行為,限制瀏覽器對每個網域的同時連線數,Chrome/Edge 為 6 條,IE 為 10 條,意思是如果網頁內含數十上百個 js、css、圖檔,瀏覽器最多只能下載其中六個,共月六條連線載完一個換下一個,即使頻寬仍夠也得乖乖排隊。HTTP/2 則允許在一條連線上多工傳輸,所有下載可同時進行,省下排隊時間便能提高效率。

好消息是 Windows 10/Server 2016+ 的 IIS 10 已內建 HTTP/2,只要有開 HTTPS 預設便已啟用 HTTP/2,若走 HTTP 則只能使用 HTTP/1.1。於是我們可分別用 http:// 或 https:// 連上同一網址,瀏覽器將使用 HTTP/1.1 及 HTTP/2 存取,剛好可以拿來對照。

Fig1_637904725899485578.png

我設計了以下實驗,用網頁載入 36 張 LINE 貼圖,img src 加上 ?_=亂數 避免 Cache,另外設計按鈕切換 http/https 測試 HTTP/1.1 或 HTTP/2:

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<style>
		.main {
			display: flex; flex-direction: row;	flex-wrap: wrap;
		}
		#u { font-size: 1.2em; background-color: cadetblue; color: white; display: inline-block; 
			 padding: 6px; }
		img { display: none; }
		img[src] { display: inline-block; max-width: 96px; max-height: 96px; margin: 3px; }
	</style>
</head>

<body>
	<div>
		<span id="u"></span> <button id="b" onclick="toggle()"></button> 
	</div>
	<div class="main">
		<img data-src="stickers/480874006.png" />
		<img data-src="stickers/480874007.png" />
		<!-- 略 -->
		<img data-src="stickers/480874040.png" />
		<img data-src="stickers/480874041.png" />
	</div>
	<script>
		let url = location.href;
		let protos = ['HTTP/1.1','HTTP/2'];
		let protoIdx = -url.indexOf('http:'); //0 or 1
		document.getElementById('u').innerText = protos[protoIdx];
		document.getElementById('b').innerText = `SWITCH TO ${protos[1 - protoIdx]}`;
		function toggle() {
			location.href = `${protoIdx ? 'http' : 'https'}:` + url.split(':')[1];
		}
		setTimeout(() => {
			let rnd = Math.random();
			[].forEach.call(document.getElementsByTagName("img"), (img) => img.src = img.getAttribute('data-src') + '?_=' + rnd);
		}, 200);
	</script>
</body>

</html>

測試時用 Edge 模擬 3G 網速讓結果明顯一點。實測影片如下,我們可以清楚觀察到 HTTP/1.1 每次同時最多下載六張圖的行為,HTTP/2 則可做到萬箭齊發,網頁載入時間快了 7 秒 (19.78s vs 12.46s)。

實測影片

見證過 HTTP/2 的加速效果,不囉嗦,馬上改了 Nginx 設定,黑暗部落格正式進入 HTTP/2 時代!

Fig2_637904725901122377.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK