Why does the following snippet speed up the code?

I solved the problem of Search Insert Position on LeetCode. The following code takes almost 9 ms to run all test cases.

class Solution { public: int searchInsert(vector<int>& nums, int target) { int lo = 0, hi = nums.size() - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (target < nums[mid]) { hi = mid - 1; } else if (target > nums[mid]){ lo = mid + 1; } else { return mid; } } return lo; } }; 

When I checked the reviews of other people, I found a strange piece of code. When I copy a snippet into my answer, the same code takes only 4 ms, which is higher than almost 99% of other solutions. Can someone explain the acceleration? Below is a snippet:

 #include <vector> #include <iostream> using namespace std; static vector<int> nums=[](){ std::ios::sync_with_stdio(false); cin.tie(NULL); return vector<int>{}; }(); 
+5
source share
1 answer

This snippet is made to "increase productivity", but at the expense of cost. I will explain:

 std::ios::sync_with_stdio(false); 

This disables the synchronization of standard C and C ++ streams. By default, they are synchronized to allow mixing of C and C ++ input-output streams (for example, cout and printf will work in a C ++ file).

 cin.tie(NULL); 

This unties the cin from cout. Again, by default they are tied so that cout is displayed before cin (i.e., resetting the output before input), so you can do, for example, the following:

 cout << "Number: "; cin >> number; 

When you untie them, you can enter the input (cin) before outputting the stream (cout).

These line lines help make the code faster, but at the cost of the cost explained earlier. Therefore use with caution.

Links: https://www.geeksforgeeks.org/fast-io-for-competitive-programming

+11
source

Source: https://habr.com/ru/post/1274850/


All Articles