go与java性能对比

go与java性能对比

2025-07-07
学习

代码 #

  • go build web.go
  • nohup ./web &
package main

import (
	"net/http"
	"strconv"
	"sync/atomic"
)

func main() {
	var count int32
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		atomic.AddInt32(&count, 1)
		_, _ = w.Write([]byte(strconv.Itoa(int(count))))
	})
	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {})
	_ = http.ListenAndServe(":8080", nil)
}
  • javac Web.java
  • nohup java Web &
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

public class Web {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8081), 0);
        server.createContext("/", new HttpHandler() {
            final AtomicInteger atomicInteger = new AtomicInteger(0);

            public void handle(HttpExchange exchange) throws IOException {
                atomicInteger.incrementAndGet();
                String response = atomicInteger.toString();
                exchange.sendResponseHeaders(200, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        });
        server.createContext("/favicon.ico", new HttpHandler() {
            public void handle(HttpExchange exchange) throws IOException {
            }
        });
        server.start();
        System.out.println("8081 start!!!");
    }
}

测试 #

  • 使用jmeter或者ab
  • apt install apache2-utils
ab -n 10000 -c 20 http://x.mm:8080/

结果 #

  • 在云服务器中,受限于网络带宽区别都不大
  • 在docker status下查看,其中ssh占用10M左右(表格内未扣除),都是jmeter下测试的结果
  • go在本机响应速度25ms,java在本机响应速度55ms
  • go build 有无-ldflags="-s -w"参数区别不大
命令 内存 吞吐量 推荐
go run web.go 84.1M 15117/sec
./web 26.4M 14259/sec
java Web.java 192.0M 2800+/sec
java Web 148.0M 2800+/sec