- exvector s;
- s.reserve(seq.size());
- exvector::const_iterator it = seq.begin(), itend = seq.end();
- while (it != itend) {
- s.push_back(it->expand(options));
- it++;
+ const_iterator cit = this->seq.begin(), end = this->seq.end();
+ while (cit != end) {
+ const ex & expanded_ex = cit->expand(options);
+ if (!are_ex_trivially_equal(*cit, expanded_ex)) {
+
+ // copy first part of seq which hasn't changed
+ std::auto_ptr<exvector> s(new exvector(this->seq.begin(), cit));
+ reserve(*s, this->seq.size());
+
+ // insert changed element
+ s->push_back(expanded_ex);
+ ++cit;
+
+ // copy rest
+ while (cit != end) {
+ s->push_back(cit->expand(options));
+ ++cit;
+ }
+
+ return s;
+ }
+
+ ++cit;