请Golang深度用户说说,现在Golang的性能可以和C比吗

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请Golang深度用户说说,现在Golang的性能可以和C比吗相关的知识,希望对你有一定的参考价值。

不可以,完全没有可比性。
Golang的优势是开发速度,C可以自由、精准的操控内存。
拿string类型举个栗子:
1、修改字符串:
golang:需要分配新内存,然后进行内存copy。
c:可直接修改,可realloc。

2、存一段data:

golang:使用[]byte类型,[]byte转成string需要进行内存拷贝(排除掉利用指针进行类型转换的情况)。
c:直接用char[],可读可写。

golang中为了语言的安全性,类似的这种限制有很多,牺牲了一部分性能。但golang的优势也是显而易见的,goroutine、chan都很好用,而c则需要自己进行进程、线程的管控。
参考技术A 不可以。
可是,一台机器从生产到报废,绝大部分的时间CPU都是跑不满的,计算机的世界本来就有大量的浪费。
程序员的时间和精力却非常宝贵,全世界99.9%的应用型程序都应该用容易开发的语言来写,为了性能而用C去写代价可能非常大。
参考技术B 有别人替你写好的 Runtime,这样直接用电动力开发速度当然快。但是缺点在于没办法精细的控制内存,而 Goroutine 的调度机制又导致你没办法高效的利用 CPU

Go 做不到像 C 那样高效,但是在一些业务场景可以取代 C。题主要实现的高性能 MQ 应可以综合考虑之后在 Go 与 C 之间作出选择。本回答被提问者采纳
参考技术C golang是编译成机器码的,,经过优化性能直逼c/c++ 参考技术D

  Go 是非常年轻的一门语言,它的主要目标是“兼具 Python 等动态语言的开发速度和 C/C++ 等编译型语言的性能与安全性”。
Go语言的推出,旨在不损失应用程序性能的情况下降低代码的复杂性,具有“部署简单、并发性好、语言设计良好、执行性能好”等优势,目前国内诸多 IT 公司均已采用Go语言开发项目。Golang编程语言零基础入门

2019年,Golang开始吊打Java性能了!!!

最近要同事debug性能,不经意间发现现在Golang性能开始吊打Java了!!!感觉Go发展神速!! 之前Go和Java基本是平手,甚至还有较大差距,请见https://www.cnblogs.com/sunsky303/p/6506663.html。借此机会对比了下,Java/Go http server最近的性能,毕竟这是后端同学最关心的问题之一!!

 

java 10 vs Golang1.12, Google上最快的2个http server性能PK, 压测10次,取平均值。

 

Java

import org.rapidoid.buffer.Buf;
import org.rapidoid.http.AbstractHttpServer;
import org.rapidoid.http.HttpStatus;
import org.rapidoid.http.MediaType;
import org.rapidoid.net.abstracts.Channel;
import org.rapidoid.net.impl.RapidoidHelper;


public class RapidoidHttpFast extends AbstractHttpServer
{
 private static final int port = 8080;
 private static final byte HOME[] = "/".getBytes();
 private static final byte HELLO_WORLD[] = "Hello World".getBytes();

 @Override
 protected HttpStatus handle(Channel ctx, Buf buf, RapidoidHelper req)
 {
  if (req.isGet.value && matches(buf, req.path, HOME))
  {
   return ok(ctx, req.isKeepAlive.value, HELLO_WORLD, MediaType.TEXT_PLAIN);
  }

  return HttpStatus.NOT_FOUND;
 }

 public static void main(String[] args) throws Exception
 {
  new RapidoidHttpFast().listen(port);
 }
}

 

sysctl -n machdep.cpu.brand_string ;java --version ;java -cp ".:/Users/wuqj/Downloads/jar_files/*" HelloWorldExample
Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
java 10 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)
19:50:33.353 [main] INFO o.r.config.RapidoidInitializer - Starting Rapidoid v5.5.5, built on 2018-05-27 15:45 UTC
19:50:33.358 [main] INFO o.r.config.RapidoidInitializer - System info | os = Mac OS X | java = 10 | process = 17435@sun-pro.local | max memory = 2048 MB | dir = /labs/java
19:50:33.639 [main] INFO org.rapidoid.env.Environment - No profiles were specified, activating \'default\' profile
19:50:33.645 [main] INFO org.rapidoid.env.Environment - No production/dev/test mode was configured, inferring mode | mode = DEV
19:50:33.645 [main] INFO org.rapidoid.env.Environment - Initialized environment | mode = DEV | profiles = [default, dev]
19:50:33.932 [main] INFO org.rapidoid.config.ConfigImpl - Loaded configuration | namespace = config | files = [built-in-config.yml, built-in-config-default.yml, built-in-config-dev.yml]
19:50:34.065 [main] INFO o.rapidoid.http.impl.HttpRoutesImpl - GET / | setup = main | roles = [] | transaction = NONE | mvc = false | cacheTTL = 0
19:50:34.072 [main] INFO org.rapidoid.setup.App - Inferred application root | main = HelloWorldExample | package =
19:50:34.080 [main] INFO org.rapidoid.setup.WatchForChanges - Watching classpath for changes... | classpath = [/labs/java/.]
19:50:34.175 [server] INFO o.r.net.impl.RapidoidServerLoop - Starting server | address = 0.0.0.0 | port = 8080 | I/O workers = 4 | sync = true | accept = non-blocking
19:50:34.399 [main] INFO org.rapidoid.setup.Setup - Server has started | setup = main | home = http://localhost:8080
19:50:34.400 [main] INFO org.rapidoid.setup.Setup - Static resources will be served from the following locations | setup = main | locations = [static, default/static]

 

ab -c100 -n100000 -k \'http://127.0.0.1:8080/\'
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Completed 100000 requests
Finished 100000 requests


Server Software:        Rapidoid
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /
Document Length:        11 bytes

Concurrency Level:      100
Time taken for tests:   2.872 seconds
Complete requests:      100000
Failed requests:        0
Keep-Alive requests:    100000
Total transferred:      17000000 bytes
HTML transferred:       1100000 bytes
Requests per second:    34822.08 [#/sec] (mean)
Time per request:       2.872 [ms] (mean)
Time per request:       0.029 [ms] (mean, across all concurrent requests)
Transfer rate:          5781.01 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.2      0      11
Processing:     0    3   1.6      2      27
Waiting:        0    3   1.6      2      27
Total:          0    3   1.6      2      27

Percentage of the requests served within a certain time (ms)
  50%      2
  66%      3
  75%      3
  80%      3
  90%      5
  95%      6
  98%      8
  99%      9
 100%     27 (longest request)

 

 

Golang

package main

import (
    "flag"
    "fmt"
    "github.com/valyala/fasthttp"
    "log"
)

var (
    addr     = flag.String("addr", ":8080", "TCP address to listen to")
    compress = flag.Bool("compress", false, "Whether to enable transparent response compression")
)

func main() {
    flag.Parse()
    h := requestHandler

    if err := fasthttp.ListenAndServe(*addr, h); err != nil {
        log.Fatalf("Error in ListenAndServe: %s", err)
    }
}

func requestHandler(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hello world")
}

 

 sysctl -n machdep.cpu.brand_string ;go version ; go run ../fasthttp/helloworldserver.go
Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
go version go1.12.4 darwin/amd64

 

ab -c100 -n100000 -k \'http://127.0.0.1:8080/\'
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Completed 100000 requests
Finished 100000 requests


Server Software:        fasthttp
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /
Document Length:        11 bytes

Concurrency Level:      100
Time taken for tests:   2.282 seconds
Complete requests:      100000
Failed requests:        0
Keep-Alive requests:    100000
Total transferred:      17000000 bytes
HTML transferred:       1100000 bytes
Requests per second:    43819.46 [#/sec] (mean)
Time per request:       2.282 [ms] (mean)
Time per request:       0.023 [ms] (mean, across all concurrent requests)
Transfer rate:          7274.72 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       7
Processing:     0    2   1.8      2     138
Waiting:        0    2   1.8      2     138
Total:          0    2   1.8      2     140

Percentage of the requests served within a certain time (ms)
  50%      2
  66%      2
  75%      2
  80%      3
  90%      4
  95%      4
  98%      6
  99%      7
 100%    140 (longest request)

 

QPS上 Go 43819.46吊打 Java 34822.08!!!

看来走Golang路线没错。 后续我有空会分析下原理。

以上是关于请Golang深度用户说说,现在Golang的性能可以和C比吗的主要内容,如果未能解决你的问题,请参考以下文章

在golang的http请求中附加用户名和密码

说说不知道的Golang中参数传递

Golang ---json解析

2019年,Golang开始吊打Java性能了!!!

golang高性能日志库zap配置示例

golang并发介绍