博客
关于我
JavaScript innerHTML和createElement效率对比
阅读量:105 次
发布时间:2019-02-26

本文共 562 字,大约阅读时间需要 1 分钟。

DOM节点操作中的innerHTML与createElement效率比较

在DOM操作中,innerHTML和createElement都是创建元素的常用方法,但它们的效率存在显著差异。本文通过测试三种方法创建1000个元素所需的时间,来比较它们的性能表现。

测试方法

本次测试选用了三种常见的DOM操作方式:

  • innerHTML字符串拼接:通过将每个元素的HTML字符串直接追加到页面中。
  • innerHTML数组拼接:将所有元素的HTML字符串收集到数组中,最后一次性拼接到页面中。
  • createElement方法:逐个创建元素并添加到页面中。
  • 测试结果

    通过实际测试,三种方法的时间差异较为明显:

  • innerHTML字符串拼接:所需时间为1245ms
  • innerHTML数组拼接:所需时间为421ms
  • createElement方法:所需时间为587ms
  • 性能对比

    从时间数据可以看出:

    • innerHTML字符串拼接的效率最低,耗时1245ms。
    • createElement方法的效率次之,耗时587ms。
    • innerHTML数组拼接的效率最高,耗时421ms。

    结论

    在实际项目中,可以根据具体需求选择合适的DOM操作方式。对于需要频繁创建元素的场景,建议使用innerHTML数组拼接方式,以获得最佳性能表现。

    转载地址:http://zfsu.baihongyu.com/

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>