zoukankan      html  css  js  c++  java
  • 对于大批量赋值功能,使用if判断是否能提高性能

    场景:

    如果对某变量进行赋值,是否需要判断一下,如果相等就不用赋值,这样会不会提高性能。

    代码如下:

     1             string a = "1234567890";
     2             string b = "1234567890";
     3 
     4             long x1=0, x2=0, x3=0;
     5 
     6             Stopwatch w = new Stopwatch();
     7 
     8             for (int x = 0; x < 10; x++)
     9             {
    10                 w.Reset();
    11                 w.Start();
    12                 for (int i = 0; i < 100000000; i++)
    13                 {
    14                     a = b;
    15                 }
    16                 w.Stop();
    17                 x1 += w.ElapsedMilliseconds;
    18                 
    19 
    20 
    21                 w.Reset();
    22                 w.Start();
    23                 for (int i = 0; i < 100000000; i++)
    24                 {
    25                     if(a != b)
    26                         a = b;
    27                 }
    28                 w.Stop();
    29                 x2 += w.ElapsedMilliseconds;                
    30 
    31 
    32                 w.Start();
    33                 for (int i = 0; i < 100000000; i++)
    34                 {
    35                     if (!a.Equals(b))
    36                         a = b;
    37                 }
    38                 w.Stop();
    39                 x3 += w.ElapsedMilliseconds;                    
    40             }
    41 
    42             System.Diagnostics.Debug.WriteLine(String.Format("直接赋值耗时:{0}ms", x1));
    43             System.Diagnostics.Debug.WriteLine(String.Format("判断赋值耗时:{0}ms", x2));
    44             System.Diagnostics.Debug.WriteLine(String.Format("判断赋值2耗时:{0}ms", x3));

    运行结果:

    直接赋值耗时:3294ms   
    判断赋值耗时:5955ms
    判断赋值2耗时:18244ms

    结论:

    判断后严重影响性能,所以无需判断,直接赋值。

  • 相关阅读:
    LeetCode 10. Regular Expression Matching
    LeetCode 5. Longest Palindromic Substring
    LeetCode 67. Add Binary
    LeetCode 8. String to Integer (atoi)
    学习笔记之C++ Primer中文版(第五版)
    LeetCode 13. Roman to Integer
    学习笔记之Macbook
    腾讯//LRU缓存机制
    腾讯//LRU缓存机制
    腾讯//子集
  • 原文地址:https://www.cnblogs.com/march3/p/3205638.html
Copyright © 2011-2022 走看看