zoukankan      html  css  js  c++  java
  • 引用计数的开销

    《efficient C++》中说,C++通过开发一种称作引用计数的垃圾回收机制来控制对象的常见、清除、复制和赋值等操作,不过天下没有免费的午餐,这样做会对象创建时速度的降低。

    例:创建引用计数类RCBigInt对类BigInt中的对象进行计数;RCObject提供计数的功能,被BigInt继承;RCPtr类通过重载 -> 和 * 操作符成为智能指针

    ///////////////////////////////////////////////////// RCObject /////////////////////////////////////////////// 
    class RCObject
    {
    public:
     void addReference() {++refCount;}
     void removeReference() {if(--refCount==0) delete this;}
     void markUnshareable() {shareable=false;}
     bool isShareable() const {return shareable;}
     bool isShared() const {return refCount>1;}
    protected:
     RCObject():refCount(0),shareable(true) {}
     RCObject(const RCObject &rhs):refCount(0),shareable(true){}
     RCObject &operator=(const RCObject& rhs) {return *this;}
     virtual~RCObject() {}
    private:
     int refCount;
     bool shareable;
    };
    //////////////////////////////////////////////////////////// BigInt //////////////////////////////////////////////
    class BigInt:public RCObject
    {
     friend BigInt operator +(const BigInt &,const BigInt&);
    public:
      BigInt (const char *);
      BigInt (unsigned=0);
      BigInt (const BigInt &);
      BigInt& operator= (const BigInt&);
      BigInt& operator+=(const BigInt&);
      ~BigInt();
      char *getDigits() const {return digits;}
      unsigned getNdigits() const {return ndigits;}
    private:
      char *digits;
      unsigned ndigits;
      unsigned size;
      BigInt (const BigInt&,const BigInt&);
      char fetch(unsigned i) const;
    };
    //////////////////////////////////////////////////////////// RCPtr<T> //////////////////////////////////////////////
    template<class T>
    class RCPtr
    {
    public:
     RCPtr(T*realPtr=0):pointee (realPtr) {init();}
     RCPtr(const RCPtr& rhs):pointee(rhs.pointee){init();}
     ~RCPtr() {if(pointee) pointee->removeReference();}
     RCPtr& operator= (const RCPtr& rhs);
     T* operator->() const {return pointee;}
     T&operator* () const {return *pointee;}
    private:
     T*pointee;
     void init();
    };
    class RCBigInt
    {
    friend RCBigInt operator+ (const RCBigInt&,const RCBigInt&);
    public:
     RCBigInt(const char*p):value(new BigInt(p)){}
     RCBigInt(unsigned u=0):value(new BigInt(u)){}
     RCBigInt(const BigInt& bi): value(new BigInt(bi)){}
    
    private:
     RCPtr<BigInt> value;
    };


     创建1000000个BigInt和RCBigInt,比较它们的运行速度,即如果是悲催的:

    引用计数的开销 - maryhp - 犀利の风林火山
    前者3049ms,后者5967ms,大概慢了1倍。
  • 相关阅读:
    「Wallace 笔记」K-D tree 区域查询时间复杂度简易证明
    「LOJ #2980」「THUSCH 2017」大魔法师
    「Wallace 笔记」快速上手回文自动机(PAM)
    「ZJU Summer Training 2020
    「AtCoder AGC002F」Leftmost Ball
    文案高手的18项修炼
    高性能MySQL实战
    300分钟搞懂 Spring Cloud
    腾讯产品启示录
    300分钟吃透分布式缓存
  • 原文地址:https://www.cnblogs.com/opama/p/6446537.html
Copyright © 2011-2022 走看看