JDBC使用PrepareStatement對(duì)性能的提升分析

下文均基于mysql-connector-java-5.1.43籍琳, mysql server version 5.6版本進(jìn)行分析菲宴。

從剛開始接觸JDBC開始,就學(xué)到使用PrepareStatement對(duì)sql進(jìn)行預(yù)編譯趋急,不用每次語(yǔ)句都進(jìn)行一次重新sql解析和編譯喝峦,相較于使用Statement能夠提高程序的性能,那么到底是用PrepareStatement對(duì)性能的提升有多大呢宣谈?

通過(guò)示例代碼:

import java.sql.*;

/**
 * Created by ZHUKE on 2017/8/18.
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test", "root", "root");
        String prepareSql = "select * from user_info where firstName = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(prepareSql);

        Statement statement = conn.createStatement();
        String statementSql = "select * from user_info where firstName= 'zhuke'";

        long nowTime = System.currentTimeMillis();

        int count = 100000;
        for (int i = 0; i < count; i++) {
            preparedStatement.setString(1, "zhuke");
            preparedStatement.execute();
        }
        long nowTime1 = System.currentTimeMillis();
        System.out.println("preparedStatement execute " + count + " times consume " + (nowTime1 - nowTime) + " ms");

        long nowTime2 = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            statement.execute(statementSql);
        }
        long nowTime3 = System.currentTimeMillis();
        System.out.println("statement execute " + count + " times consume " + (nowTime3 - nowTime2) + " ms");

    }
}

執(zhí)行同樣的語(yǔ)句100000次愈犹,得到的結(jié)果如下:

測(cè)試結(jié)果

14588 : 14477,這就是我一直深信的性能提升?漩怎?勋颖?

一定是哪里出了問題,通過(guò)查找資料知道勋锤,PrepareStatement會(huì)將帶有參數(shù)占位符饭玲?的sql語(yǔ)句提交到mysql服務(wù)器,服務(wù)器會(huì)對(duì)sql語(yǔ)句進(jìn)行解析和編譯叁执,將編譯后的sql id返回給客戶端茄厘,客戶端下次值需要將參數(shù)值和sql id發(fā)送到服務(wù)器即可。以此節(jié)省了服務(wù)器多次重復(fù)編譯同一sql語(yǔ)句的開銷谈宛,而且因?yàn)椴挥妹看味及l(fā)送完整sql內(nèi)容次哈,也一定程度上節(jié)省了網(wǎng)絡(luò)開銷。

那么為什么以上代碼中吆录,PrepareStatement沒有實(shí)現(xiàn)性能提升呢窑滞?
通過(guò)開啟mysql的詳細(xì)日志,對(duì)PrepareStatement的執(zhí)行來(lái)一探究竟恢筝。

preparedStatement.setString(1, "zhuke");
preparedStatement.execute();

mysql日志如下:

PrepareStatement執(zhí)行mysql日志

通過(guò)mysql日志我們可以看到哀卫,通過(guò)PrepareStatement的方式,每次執(zhí)行發(fā)送給mysql服務(wù)器的依然是完整的參數(shù)拼接完成后的sql語(yǔ)句撬槽,并沒有利用到上述的服務(wù)器預(yù)編譯的特性此改。

通過(guò)mysql-connector-java(5.1.43版本)連接驅(qū)動(dòng)的源碼來(lái)查找原因。

public java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
    synchronized (getConnectionMutex()) {
        ……

        if (this.useServerPreparedStmts && getEmulateUnsupportedPstmts()) {
            canServerPrepare = canHandleAsServerPreparedStatement(nativeSql);
        }
        //如果useServerPreparedStmts配置為true侄柔,且服務(wù)器支持sql預(yù)編譯優(yōu)化共啃,則執(zhí)行服務(wù)器sql優(yōu)化
        if (this.useServerPreparedStmts && canServerPrepare) {
            if (this.getCachePreparedStatements()) {
                synchronized (this.serverSideStatementCache) {
                    ……
        } else {//否則執(zhí)行本地預(yù)編譯
            ……
        }

        return pStmt;
    }
}

服務(wù)器支持預(yù)編譯的情況下,那么就只由useServerPreparedStmts 控制是否進(jìn)行服務(wù)器預(yù)編譯了暂题。而從源碼中又知道其默認(rèn)值為false勋磕。那么如果不顯式配置useServerPreparedStmts =true,就不會(huì)進(jìn)行服務(wù)器預(yù)編譯敢靡,而只執(zhí)行本地預(yù)編譯挂滓。

Important change: Due to a number of issues with the use of server-side prepared statements, Connector/J 5.0.5 has disabled their use by default. The disabling of server-side prepared statements does not affect the operation of the connector in any way.
To enable server-side prepared statements, add the following configuration property to your connector string:
useServerPrepStmts=true
The default value of this property is false (that is, Connector/J does not use server-side prepared statements).
通過(guò)查找MySQL官網(wǎng)發(fā)現(xiàn),驅(qū)動(dòng)文件在版本 5.0.5后將設(shè)為了false啸胧,所以需要手動(dòng)指定和開啟服務(wù)器預(yù)編譯功能赶站。
https://dev.mysql.com/doc/relnotes/connector-j/5.1/en/news-5-0-5.html

通過(guò)在url鏈接中添加參數(shù)useServerPreparedStmts =true開啟服務(wù)器預(yù)編譯。
現(xiàn)在我們看到mysql日志信息如下:

useServerPreparedStmts =true時(shí)mysql日志信息

此時(shí)我們看到纺念,開啟了服務(wù)器預(yù)編譯后贝椿,mysql服務(wù)器會(huì)首先prepare
預(yù)編譯

select * from user_info where firstName = ?

語(yǔ)句。

再次實(shí)驗(yàn)以上代碼陷谱,看看性能提升了多少:

開啟useServerPreparedStmts 后執(zhí)行結(jié)果

13312 : 14535烙博,性能提升了8.4%.

與之對(duì)應(yīng)的還有一個(gè)參數(shù):cachePrepStmts表示服務(wù)器是否需要緩存prepare預(yù)編譯對(duì)象瑟蜈。

// 關(guān)閉cachePrepStmts時(shí)新建兩個(gè)preparedStatement 
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test?useServerPrepStmts=true", "root", "root");
String prepareSql = "select * from user_info where firstName = ?";
PreparedStatement preparedStatement = conn.prepareStatement(prepareSql);

preparedStatement.setString(1, "zhuke");
preparedStatement.execute();
preparedStatement.close();

preparedStatement = conn.prepareStatement(prepareSql);
preparedStatement.setString(1, "zhuke1");
preparedStatement.execute();
preparedStatement.close();
關(guān)閉cachePrepStmts時(shí)新建兩個(gè)preparedStatement

可以看到此時(shí),針對(duì)完全相同的sql語(yǔ)句渣窜,服務(wù)器進(jìn)行了兩次預(yù)編譯過(guò)程铺根。

那么當(dāng)我們開啟cachePrepStmts的時(shí)候呢?

// 關(guān)閉cachePrepStmts時(shí)新建兩個(gè)preparedStatement 
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test?useServerPrepStmts=true&cachePrepStmts=true", "root", "root");
String prepareSql = "select * from user_info where firstName = ?";
PreparedStatement preparedStatement = conn.prepareStatement(prepareSql);

preparedStatement.setString(1, "zhuke");
preparedStatement.execute();
preparedStatement.close();

preparedStatement = conn.prepareStatement(prepareSql);
preparedStatement.setString(1, "zhuke1");
preparedStatement.execute();
preparedStatement.close();
開啟開啟cachePrepStmts時(shí)的mysql日志

可以看到乔宿,開啟cachePrepStmts時(shí)位迂,mysql服務(wù)器只進(jìn)行了一次預(yù)編譯過(guò)程。

通過(guò)閱讀源碼發(fā)現(xiàn)详瑞,當(dāng)開啟cachePrepStmts時(shí)掂林,客戶端會(huì)以sql語(yǔ)句作為鍵,預(yù)編譯完成后的對(duì)象PrepareStatement作為值坝橡,保存在Map中泻帮,以便下次可以重復(fù)利用和緩存。

//prepareStatement關(guān)閉時(shí)计寇,將對(duì)象存入緩存中
public void close() throws SQLException {
        MySQLConnection locallyScopedConn = this.connection;

        if (locallyScopedConn == null) {
            return; // already closed
        }

        synchronized (locallyScopedConn.getConnectionMutex()) {
            if (this.isCached && isPoolable() && !this.isClosed) {
                clearParameters();
                this.isClosed = true;
                //緩存預(yù)編譯對(duì)象
                this.connection.recachePreparedStatement(this);
                return;
            }

            realClose(true, true);
        }
    }


public void recachePreparedStatement(ServerPreparedStatement pstmt) throws SQLException {
        synchronized (getConnectionMutex()) {
            if (getCachePreparedStatements() && pstmt.isPoolable()) {
                synchronized (this.serverSideStatementCache) {
                    Object oldServerPrepStmt = this.serverSideStatementCache.put(makePreparedStatementCacheKey(pstmt.currentCatalog, pstmt.originalSql), pstmt);
                    if (oldServerPrepStmt != null) {
                        ((ServerPreparedStatement) oldServerPrepStmt).isCached = false;
                        ((ServerPreparedStatement) oldServerPrepStmt).realClose(true, true);
                    }
                }
            }
        }
    }


結(jié)論

使用mysql的預(yù)編譯對(duì)象PrepateStatement時(shí)刑顺,一定需要設(shè)置useServerPrepStmts=true開啟服務(wù)器預(yù)編譯功能,設(shè)置cachePrepStmts=true開啟客戶端對(duì)預(yù)編譯對(duì)象的緩存饲常。

參考資料:
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
http://www.cnblogs.com/justfortaste/p/3920140.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市狼讨,隨后出現(xiàn)的幾起案子贝淤,更是在濱河造成了極大的恐慌,老刑警劉巖政供,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件播聪,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡布隔,警方通過(guò)查閱死者的電腦和手機(jī)离陶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)衅檀,“玉大人招刨,你說(shuō)我怎么就攤上這事“Ь” “怎么了沉眶?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)杉适。 經(jīng)常有香客問我谎倔,道長(zhǎng),這世上最難降的妖魔是什么猿推? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任片习,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘藕咏。我一直安慰自己状知,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布侈离。 她就那樣靜靜地躺著试幽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪卦碾。 梳的紋絲不亂的頭發(fā)上铺坞,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音洲胖,去河邊找鬼济榨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛绿映,可吹牛的內(nèi)容都是我干的擒滑。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼叉弦,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼丐一!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起淹冰,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤库车,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后樱拴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體柠衍,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年晶乔,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了珍坊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡正罢,死狀恐怖阵漏,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情翻具,我是刑警寧澤袱饭,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站呛占,受9級(jí)特大地震影響虑乖,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜晾虑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一疹味、第九天 我趴在偏房一處隱蔽的房頂上張望仅叫。 院中可真熱鬧,春花似錦糙捺、人聲如沸诫咱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)坎缭。三九已至,卻和暖如春签钩,著一層夾襖步出監(jiān)牢的瞬間掏呼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工铅檩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留憎夷,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓昧旨,卻偏偏與公主長(zhǎng)得像拾给,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子兔沃,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容