DB访问比在java中访问集合更昂贵吗? [英] Are DB hits costlier than accessing collection in java?

查看:119
本文介绍了DB访问比在java中访问集合更昂贵吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚实现了一个设计,我已经缓存了一些数据在hashmap和检索的数据,而不是从DB查询相同的数据。



我的想法是否正确? p>

解决方案

如果你想想当你和数据库交谈时会发生什么,你可以自己回答:


  1. 您的程序必须将查询发送到数据库。根据数据库服务器是否正在运行或正在网络上的其他位置运行,这可能需要几微秒到几毫秒的时间。

  2. 数据库服务器必须解析您的查询并生成执行计划。根据服务器,它可能缓存频繁执行的查询的执行计划。

  3. 数据库服务器必须执行您的计划,读取访问数据所需的任何磁盘块。每次磁盘访问将需要几十毫秒。根据表的大小以及索引的建立情况,您的查询可能需要几秒钟。

  4. 数据库服务器必须打包数据并将其发送回应用程序。再次,根据是在进程还是在网络上,这将需要几微秒到几毫秒,并且会根据返回的数据量而有所不同。

  5. 您的应用程序必须将检索数据为有用的形式。


  6. 相比之下,对散列数据结构的查找需要一些内存访问,这可能需要几个纳秒。区别在于几个数量级


    Just implemented a design where i had cached some data in hashmap and retrieved data from it instead querying the same data from DB.

    Is my thinking correct ?

    解决方案

    You can answer this yourself if you think through what happens when you talk to the database:

    1. Your program has to send the query to the database. Depending on whether the database server is running in-process or somewhere else on the network, this may take anywhere from a few microseconds to a few milliseconds.
    2. The database server has to parse your query and generate an execution plan. Depending on the server, it might cache an execution plan for frequently executed queries. If not, plan on another few microseconds to generate the plan.
    3. The database server has to execute your plan, reading whatever disk blocks are needed to access the data. Each disk access will take tens of milliseconds. Depending on how large the table is, and how well it is indexed, your query might take seconds.
    4. The database server has to package up the data and send it back to the application. Again, depending on whether it's in-process or across the network, this will take microseconds to milliseconds, and it will vary depending on how much data is sent back.
    5. Your application must convert the retrieved data into a useful form. This is probably a microsecond or less.

    By comparison, a lookup on a hashed data structure requires a few memory accesses, which may take a few nanoseconds each. The difference is several orders of magnitude.

    这篇关于DB访问比在java中访问集合更昂贵吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆