[LLVMbugs] [Bug 20190] New: Feature Request: Spot redundant lambda and std::function<> construction/destruction in loops

bugzilla-daemon at llvm.org bugzilla-daemon at llvm.org
Wed Jul 2 02:54:13 PDT 2014


http://llvm.org/bugs/show_bug.cgi?id=20190

            Bug ID: 20190
           Summary: Feature Request: Spot redundant lambda and
                    std::function<> construction/destruction in loops
           Product: clang
           Version: unspecified
          Hardware: PC
                OS: Windows NT
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Static Analyzer
          Assignee: kremenek at apple.com
          Reporter: s_llvm at nedprod.com
                CC: llvmbugs at cs.uiuc.edu
    Classification: Unclassified

An inefficient code pattern I keep seeing looks a bit like this:

std::vector<std::function<void(int)>> vs;
for(...)
{
  double &f;
  vs.push_back(std::bind([](int, double) {...}, _1, f));
}

This code needlessly constructs a lambda every loop iteration, plus a
std::function every loop iteration. A more efficient implementation might be
this:

std::vector<std::function<void(int)>> vs;
for(...)
{
  double &f;
  static auto c=[](int, double) {...};
  vs.push_back(std::bind(c, _1, f));
}

Which saves on a lambda construction. Or even better again:

std::vector<std::function<void(int)>> vs;
std::function<void(int, double)> c=[](int, double) {...};
for(...)
{
  double &f;
  vs.push_back(std::bind(c, _1, f));
}

Which also saves on a std::function construction.

This may seem asinine for the clang static analyser to warn about, but many
programmers don't seem to realise that declaring lambdas inside a loop equals a
construction/destruction round. I myself find myself doing it because it's easy
to forget you're in a loop, and then you kick yourself later when you see the
assembler copying memory around needlessly.

A clang static analyser warning here would be useful.

Niall

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20140702/7e391394/attachment.html>


More information about the llvm-bugs mailing list