您的位置 首页 php

php和go写入MySQL速度谁更快?

php和go插入 mysql 数据速度的比较

pk

1. 建表

表结构,简单,只有两个字段,name和age

CREATE TABLE `user1` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`name` varchar(10) NOT NULL DEFAULT ”,

`age` int(10) unsigned NOT NULL DEFAULT ‘0’,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8

测试环境,在同一服务器上。

为了尽可能准确,都没有用框架,用的简单代码

1. 插入1w条记录

结果比较

php

php

go

go

结果:php和go基本都是11s左右,速度 基本相当。

2. 插入10w条记录

php

php10

go

go10

结果可以看出来,php不到2分钟,而go需要2分钟以上,php更快一点。

下面附上测试代码,有兴趣的可以测一下:

php:

 function getMillisecond() {
  list($s1, $s2) = explode(' ', microtime());
  return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}

$ dsn  = 'mysql:dbname=demo;host=127.0.0.1';
$user = "root";
$password = '123456';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
$count = 100000;
$start = getMillisecond();
for($i=0;$i<$count;$i++){
$age =  rand (20,40);
$name = "user_".rand(100,999);
$ sql  = "insert into user (id,name,age) values('',?,?)";
$stat = $dbh->prepare($sql);
$stat->execute([$name, $age]);
}
$time = getMillisecond()-$start;
echo "time is ".$time." ms ";  

go:

 package main

import (
"fmt"
"math/rand"
"strconv"
"time"
_ " github .com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)

const NUM = 100000

var (
userName  string = "root"
password  string = "123456"
ipAddrees string = "127.0.0.1"
port      int    = 3306
dbName    string = "demo"
charset   string = "utf8"
)

func connectMysql() *sqlx.DB {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddrees, port, dbName, charset)
Db, err := sqlx.Open("mysql", dsn)
if err != nil {
fmt.Printf("mysql connect failed, detail is [%v]", err.Error())
}
return Db
}

func addRecord(Db *sqlx.DB) {

for i := 0; i < NUM; i++ {
name := "user_" + strconv.Itoa(rand.Intn(999))
age := rand.Intn(40)
_, err := Db.Exec("insert into user1 (id,name,age) values(?,?,?)", 0, name, age)
if err != nil {
fmt.Printf("data insert faied, error:[%v]", err.Error())
return
}
}
}

func main() {

var Db *sqlx.DB = connectMysql()
defer Db.Close()
t1 := time.Now()
rand.Seed(time.Now().UnixNano())
addRecord(Db)
t2 := time.Now()
fmt.Println(t2.Sub(t1))
}  

以上纯属个人见解,欢迎各位同行指正!

文章来源:智云一二三科技

文章标题:php和go写入MySQL速度谁更快?

文章地址:https://www.zhihuclub.com/78978.shtml

关于作者: 智云科技

热门文章

网站地图