IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

js如何清空数组最快?

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

方式1:splice函数

arrayObject.splice(index,howmany,element1,…..,elementX)

index:必选,规定从何处添加/删除元素。

howmany:必选,规定应该删除多少元素。未规定此参数,则删除从 index 开始到原数组结尾的所有元素。

element1:可选,规定要添加到数组的新元素。

<script type ="text/javascript">  
  var arr = [1,2,3,4];  
   arr.splice(0,arr.length);  </script>  

方式2:给数组的length赋值为0

<script type ="text/javascript">  
  var arr = [1,2,3,4];  
   arr.length = 0;
</script> 

赋予数组的长度小于本身的长度,数组中后面的元素将被截断。

赋予数组的长度大于本身的长度,将扩展数组长度,多的元素为undefined。

方式3:直接赋予新数组 []

<script type ="text/javascript">  
  var arr = [1,2,3,4];  
   arr = [];
</script> 

这种方式为将arr重新复制为空数组,之前的数组如果没有被引用,将等待垃圾回收。

效率比较:

效率测试代码如下:

<script>
    var a = [];
    var b = [];
    var c = [];
    for(var i =0 ; i < 100000000;i++){
        a.push(i);
    }
    console.time('splice');
    a.splice(0,a.length); 
    console.timeEnd('splice');

    for(var i =0 ; i < 100000000;i++){
        b.push(i);
    }
    console.time('length');
    b.length = 0;
    console.timeEnd('length');

    for(var i =0 ; i < 100000000;i++){
        c.push(i);
    }
    console.time('赋值[]');
    c = [];
    console.timeEnd('赋值[]');
</script>

测试结果:

splice: 0.010986328125ms
length: 0.009033203125ms
赋值[]: 0.024169921875ms

多次测试发现第二种方式最快,第一种其次,大数据量下 第三种最慢。

测试结果可能不严谨。大家仅做参考。

72_1.png

文章永久链接:https://tech.souyunku.com/?p=36005


Warning: A non-numeric value encountered in /data/wangzhan/tech.souyunku.com.wp/wp-content/themes/dux/functions-theme.php on line 1154
赞(82) 打赏



未经允许不得转载:搜云库技术团队 » js如何清空数组最快?

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码
IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

评论 抢沙发

大前端WP主题 更专业 更方便

联系我们联系我们

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

微信扫一扫打赏


Fatal error: Uncaught Exception: Cache directory not writable. Comet Cache needs this directory please: `/data/wangzhan/tech.souyunku.com.wp/wp-content/cache/comet-cache/cache/https/tech-souyunku-com/index.q`. Set permissions to `755` or higher; `777` might be needed in some cases. in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php:367 Stack trace: #0 [internal function]: WebSharks\CometCache\Classes\AdvancedCache->outputBufferCallbackHandler() #1 /data/wangzhan/tech.souyunku.com.wp/wp-includes/functions.php(5109): ob_end_flush() #2 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(303): wp_ob_end_flush_all() #3 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(327): WP_Hook->apply_filters() #4 /data/wangzhan/tech.souyunku.com.wp/wp-includes/plugin.php(470): WP_Hook->do_action() #5 /data/wangzhan/tech.souyunku.com.wp/wp-includes/load.php(1097): do_action() #6 [internal function]: shutdown_action_hook() #7 {main} thrown in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php on line 367